Loops Example
Loops Example
1
Code Explanation:
1. Including the iostream header file in our code. It will allow us to read
from and write to the console /support.
2. Including the std namespace so as to use its classes
and functions without calling it.
3. Calling the main() function inside which the logic of the program
should be added. The { marks start of body of the main() function.
4. Creating a for loop. The initialization creates an integer variable x and
assigns it a value of 0. The condition states that the value of x must be
less than 5. The increment increases the value of x by 1 after every
iteration. The { marks the beginning of the body of the for loop.
5. To print the value of variable x alongside other text on the console. The
endl is a C++ keyword meaning end line. The cursor will print in the
next line in the next iteration.
6. End of the loop body.
7. The main() function should return an value if the program runs fine.
8. End of the body of the main() function.
2
for (x = 1; x <= num; ++x) {
factorial *= x; // factorial = factorial * x;
}
cout << "Factorial of " << num << " = " << factorial;
return 0;
}
Output:
Code Explanation:
1. Including the iostream header file in our code. It will allow us to read from and write to
the console.
2. Including the std namespace so as to use its classes and functions without calling it.
3. Calling the main() function inside which the logic of the program should be added.
4. The { marks start of body of the main() function.
3
5. Declaring integer variables, x, num, and factorial. The variable factorial has been
assigned a value of 1.
6. Printing some text on the console.
7. Prompting user to enter a value for variable num.
8. Creating a for loop. The initialization creates an integer variable x and assigns it a value
of 1. The condition states that the value of x must be less than or equal to value of
variable num. The increment increases the value of x by 1 after every iteration. The
{ marks the beginning of the body of the for loop.
9. Calculating the value of factorial using the formula factorial = factorial * x.
10. End of the loop body.
11. To print the value of variables num and factorial alongside other text on the console.
12. The main() function should return an value if the program runs fine.
13. End of the body of the main() function.
4
Example: Create a Calculator using the switch Statement
// Program to build a simple calculator using switch Statement
#include <iostream>
usingnamespacestd;
intmain() {
char oper;
float num1, num2;
cout<<"Enter an operator (+, -, *, /): ";
cin>> oper;
cout<<"Enter two numbers: "<<endl;
cin>> num1 >> num2;
switch (oper) {
case'+':
cout<< num1 <<" + "<< num2 <<" = "<< num1 + num2;
break;
case'-':
cout<< num1 <<" - "<< num2 <<" = "<< num1 - num2;
break;
case'*':
cout<< num1 <<" * "<< num2 <<" = "<< num1 * num2;
break;
case'/':
cout<< num1 <<" / "<< num2 <<" = "<< num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout<<"Error! The operator is not correct";
break;
}
return0;
}
5
Output 1
Output 2
Output 3
Output 4
Output 5
6
Enter an operator (+, -, *, /): ?
Enter two numbers:
2.3
4.5
Error! The operator is not correct.
2. We then prompt the user to enter two numbers, which are stored in the float
variables num1 and num2 .
3. The switch statement is then used to check the operator entered by the user:
o If the user enters + , addition is performed on the numbers.
o If the user enters - , subtraction is performed on the numbers.
o If the user enters * , multiplication is performed on the numbers.
o If the user enters / , division is performed on the numbers.
o If the user enters any other character, the default code is printed.
Let’s take the same example but this time with break statement.
#include <iostream>
int main(){
int i=2;
switch(i) {
case 1:
cout<<"Case1 "<<endl;
break;
7
case 2:
cout<<"Case2 "<<endl;
break;
case 3:
cout<<"Case3 "<<endl;
break;
case 4:
cout<<"Case4 "<<endl;
break;
default:
cout<<"Default "<<endl;
return 0;
Output:
4. Case2
5. Now you can see that only case 2 got executed, rest of the subsequent
cases were ignored.
8
#include <iostream>
using namespace std;
int main()
{
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
return0;
}}
9
#include <iostream>
int main(){
// Outputs Volvo
return 0;}
int main() {
10
return 0;
Output
25
50
75
100
#include <iostream>
int main()
a[3] = 60;
return 0;
Output
60
11
Traversing an Array in C++
To traverse an array, for loop is used.
Example
#include <iostream>
#include <string>
int main() {
return 0;
Output
Apple
Mango
12
Banana
Orange
Grapes
Example
// Program to take values of the array from the user and print the array
#include<iostream>
usingnamespace std;
intmain(){
int a[5];
cout <<"Enter the values of an integer array:"<< endl;
Output
Enter the values of an integer array:
1
2
3
4
5
Displaying integers:
1
2
3
13
4
5
Variables of string type are able to store sequences of characters, such as words or sentence.
The program needs to include the header where the type is defined within the standard library
(header <string>):
// my first string
#include <iostream>
#include <string>
int main ()
string mystring;
return 0;
14
C++ String
#include <iostream>
15
cout << "This is a greeting message: ";
return 0;
}
Output:
#include <iostream>
int main(){
cout<<greet<<endl;
16
Output:
Example: string
#include <iostream>
usingnamespacestd;
intmain()
chars[] = "GeeksforGeeks";
return0;
Output
GeeksforGeeks
17
Example: string
#include <iostream>
usingnamespacestd;
intmain()
return0;
Output:
ggggg
18
// C++ Program to demonstrate C-style string declaration
#include <iostream>
usingnamespacestd;
intmain()
chars3[4] = "gfg";
chars4[] = "gfg";
return0;
Output
s1 = gfg
s2 = gfg
s3 = gfg
19
s4 = gfg
Using Cin
The simplest way to take string input is to use the cin command along with the stream
extraction operator (>>).
Syntax:
cin>>s;
Example:
C++
#include <iostream>
usingnamespacestd;
intmain() {
string s;
cout<<"Enter String"<<endl;
cin>>s;
return0;
Output
Enter String
String is:
20
There are 3 types of loops in C++.
for loop
while loop
do...while loop
#include <iostream>
int main() {
return 0;
Output
1 2 3 4 5
21
Decrement number for loops
# include <iostream>
using namespace std;
int main()
{
for(int i = 5; i>0;)
{
i--;
cout <<i<<" ";
}
return 0;
}
The output of this code would be 4 3 2 1 0.
#include <iostream>
int main() {
return 0;
22
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
#include <iostream>
int main() {
sum = 0;
sum += i;
return 0;
23
Note that we have used a for loop.
Here,
+ ... + 10 .
Here, for every value in the collection , the for loop is executed and the value
is assigned to the variable .
24
Code 3: Printing half pyramid using Alphabets
Similarly, we will replace the �x with the desired alphabets to print a pyramid of alphabets.
Source Code:
#include<bits/stdc++.h>
usingnamespace std;
int main(){
int rows;
// Getting the number of rows.
cout <<"Enter the Number of rows - ";
cin >> rows;
return0;
}
Output:
25
Source Code:
#include<bits/stdc++.h>
usingnamespace std;
int main(){
int rows;
// Getting the number of rows.
cout <<"Enter the Number of rows - ";
cin >> rows;
return0;
}
Output:
the half-star pyramid pattern as he wishes, then the result will be displayed
on the screen:
Code:
26
#include<iostream>
usingnamespace std;
intmain()
{
int i, j, n;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j =1; j <= i; j++)
{
cout <<"* ";
}
//Ending line after each row
cout <<"\n";
}
return0;
}
Example 2- Program in C++ to print an inverted
half-star pyramid pattern
In the following C++ program, the user can enter the number of rows to
print the inverted half-star pyramid pattern as he wishes, then the result will
Code:
#include<iostream>
27
usingnamespace std;
intmain()
{
int i, j, n;
cout <<"Enter number of rows: ";
cin >> n;
for(i = n; i >=1; i--)
{
for(j =1; j <= i; j++)
{
cout <<"* ";
}
// ending line after each row
cout <<"\n";
}
return0;
}
Example 3- Program in C++ to print star pyramid
pattern
In the following program, the user can enter the number of rows to print the
star pyramid pattern as he wishes, then the result will be displayed on the
screen:
#include<iostream>
int main()
int n, s, i, j;
28
cin >> n;
}
}
29
Example 4- Program in C++ to enter a number of
rows to print the star pyramid pattern
In the following program, the user can enter a number of rows to print the
star pyramid pattern as he wishes, then the result will be displayed on the
screen:
#include<iostream>
int main()
int n, s, i, j;
cin >> n;
return 0;
}
Example 5– Program in C++ to print an inverted
star pyramid pattern
In the following program, the user can enter a number of rows to print the
inverted star pyramid pattern as he wishes, then the result will be displayed
on the screen:
Code:
#include<iostream>
usingnamespace std;
intmain()
{
int n, s, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i = n; i >=1; i--)
{
//for loop to put space
for(s = i; s < n; s++)
cout <<" ";
//for loop for displaying star
for(j =1; j <= i; j++)
cout <<"* ";
// ending line after each row
31
cout <<"\n";
}
return0;
}
Example 7 – Program to print full star diamond
pattern in C++
In the following program, the user can enter the number of rows for the
Code:
#include<iostream>
usingnamespace std;
intmain()
{
int n, s, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =0; i <= n; i++)
{
for(s = n; s > i; s--)
cout <<" ";
for(j=0; j<i; j++)
cout <<"* ";
cout <<"\n";
}
32
for(i =1; i < n; i++)
{
for(s =0; s < i; s++)
cout <<" ";
for(j = n; j > i; j--)
cout <<"* ";
// ending line after each row
cout <<"\n";
}
return0;
}
Example 8
#include<iostream>
usingnamespace std;
intmain()
{
int n, i , j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j =1; j <= i; j++)
{
cout <<"*";
}
cout<<"\n";
}
for(i = n; i >=1; i--)
{
for(j =1; j <= i; j++)
33
{
cout <<"*";
}
// ending line after each row
cout<<"\n";
}
return0;
}
Example 9
Code:
#include<iostream>
usingnamespace std;
intmain()
{
int n, i, j;
cout <<"Enter number of rows: ";
cin >> n;
for(i =1; i <= n; i++)
{
for(j = i; j < n; j++)
{
cout <<" ";
}
for(j =1; j <= i; j++)
{
cout <<"*";
}
cout <<"\n";
34
}
for(i = n; i >=1; i--)
{
for(j = i; j <= n; j++)
{
cout <<" ";
}
for(j =1; j < i; j++)
{
cout<<"*";
}
// ending line after each row
cout<<"\n";
}
return0;
}
hollow star pyramid pattern as he wishes, then the result will be displayed on
the screen:
Code:
#include<iostream>
usingnamespace std;
35
intmain()
{
int r, i, j, s;
cout <<"Enter number of rows: ";
cin >> r;
for(i =1; i <= r; i++)
{
//for loop to put space in pyramid
for(s = i; s < r; s++)
cout <<" ";
//for loop to print star
for(j =1; j <=(2* r -1); j++)
{
if(i == r || j ==1|| j ==2*i -1)
cout <<"*";
else
cout <<" ";
}
//ending line after each row
cout <<"\n";
}
return0;
}
36
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:
int main() {
int i = 0;
while (i < 5) {
return 0;
Output:
int main(){
38
int i = 1;
i++;}
return 0;
Output:
Explanation:
1. In the above code snippet, we declare and initialize a variable i with the value of
1. We then make use of a while loop to print some statements.
2. A test expression (i<5) is checked, and the control moves to the first statement.
3. We use the cout statement inside the while loop to print the statement 'You are
unstoppable.
4. After the statement gets printed for the first time, the value of i then becomes 2
because of the update expression (i++).
5. The program again checks the condition, which is true, and the statement is
executed for the second time.
6. This is continued until i becomes 6, the condition (6<5) becomes false, and we
exit the loop.
39
Example 3: Display Numbers from 1 to 5 do...while Loop
// C++ Program to print numbers from 1 to 5
#include<iostream>
usingnamespacestd;
intmain(){
int i = 1;
return0;
}
Run Code
Output
1 2 3 4 5
#include<iostream>
usingnamespacestd;
intmain(){
int number = 0;
int sum = 0;
40
do {
sum += number;
return0;
}
Run Code
Output 1
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
Here, the do...while loop continues until the user enters a negative number.
When the number is negative, the loop terminates; the negative number is not
added to the sum variable.
A do-while loop is similar to the while loop with one major difference. It
is an exit-controlled loop in which the condition is checked after
41
executing the body of the loop, unlike the while loop, which is an entry-
controlled loop. This can be used as an alternative to a while loop as
well.
#include <iostream>
int main(){
int x = 9;
do {
x++;
return 0;}
42
#include<conio.h>
int gvar1;
int main()
Argument
Argument
43
//int z=x+y; this means function Definition
int x=x*2;
cout<<"x=="<<x<<endl;
cout<<"y=="<<y<<endl;
int z=x+y;
rerurn z;
44
C++ Function example by values ,references code
explanation
#include<iostream>
a=4;
b=5;
int main()
int a=2,b=3;
45
//this means show the output 2 and 3 not show 4 and 5 b/c
cout<<a<<endl;
cout<<b<<endl;
test(a, b);
variables"<<endl;
cout<<a<<endl;
cout<<b<<endl;
return 0;
46
#include<conio.h>
int gvar1;
int main()
Argument
Argument
47
// cout<<"x=="<<y<<endl; this is display the values of
int x=x*2;
cout<<"x=="<<x<<endl;
cout<<"y=="<<y<<endl;
int z=x+y;
rerurn z;
48
#include<iostream>
using namespace std;
int main()
{
int odd[10]={1,3,5,7,9,11,13,15,17,19};
cout<<odd[7]<<endl; this means show the number of
15
odd[7]=67;this means show 15 by replace by 67
cout<<odd[7]<<endl;
cout<<odd[0]+56<<" the number is"<<endl; this ishow
to add initial number `1+56= the result is 57
cout<<odd[0]<<" the number is"<<endl;
cout<<odd[1]<<" the number is"<<endl;
cout<<odd[2]<<" the number is"<<endl;
cout<<odd[3]<<" the number is"<<endl;
cout<<odd[4]<<" the number is"<<endl;
cout<<odd[5]<<" the number is"<<endl;
cout<<odd[6]<<" the number is"<<endl;
cout<<odd[7]<<" the number is"<<endl;
cout<<odd[8]<<" the number is"<<endl;
cout<<odd[9]<<" the number is"<<endl;
return 0;
}
49
one dimensional array example code
#include<iostream>
int main()
Output:
Array1 elements: 1020304050
Initialize One Dimensional Array in C++ :
#include<stdio.h>
int main () {
int arr[10];
int i,j;
50
for ( i = 0; i < 10; i++ ) {
arr[i] = i + 10;
return 0;
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
51
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{2,3,4},{7,8,9},{2,5,1},{8,3,2}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
}//end of j
}//end of i
return 0;
52
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[5][4]={{1,2,3},{2,3,4},{3,4,5},{4,5,6},{5,6,7}};
for(i=0;i<5;i++){
for(j=0;j<4;j++){
return 0;
53