Loops
Loops
Loop:
In computer programming, loops are used to repeat a block of code.
For example, let's say we want to show a message 100 times. Then instead of writing the print
statement 100 times, we can use a loop.
There are 3 types of loops in C++.
for loop
while loop
do...while loop
1
C++ Infinite for loop
If the condition in a for loop is always true, it runs forever (until memory is full). For example,
// infinite for loop
for(int i = 1; i > 0; i++) {
// block of code
}
In the above program, the condition is always true which will then run the code for infinite times.
Nested loop
A loop within another loop is called a nested loop.
Example:
#include <iostream>
using namespace std;
int main()
{
int i,j;
for(i=1;i<4;i++)
{
for(j=1;j<5;j++)
cout<<j<<" ";
cout<<endl;
}
return 0;
}
Output
1234
1234
1234
2
}
Output
12345
3
Output 2
Enter a number: -6
The sum is 0.
4
C++ switch..case Statement
The switch statement allows us to execute a block of code among many alternatives.
The syntax of the switch statement in C++ is:
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
Example: Create a Calculator using the switch Statement
#include <iostream>
using namespace std;
int main() {
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;
}
return 0;
}
Output 1
Enter an operator (+, -, *, /): +
5
Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8
Output 2
Enter an operator (+, -, *, /): -
Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2
Output 3
Enter an operator (+, -, *, /): *
Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35
Output 4
Enter an operator (+, -, *, /): /
Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111
Output 5
Enter an operator (+, -, *, /): ?
Enter two numbers:
2.3
4.5
Error! The operator is not correct.
6
cout << "Enter n" << i << ": ";
cin >> num;
if(num < 0.0)
{
goto jump;
}
sum += num;
}
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95