info@tutsfinder.in

## Loops

Looping statements provides a way to repeat a set of statements at a given place<./p>

Types of looping statements –

1. for loop

2. while loop

3. do while loop

1. for statement - The for statement provides a compact way to iterate over a range of values.

For loop is used to repeatedly loops until a particular condition is satisfied

```for(initialization; termination; increment)
{
statement(s)
}
```

```#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=5; i++){

cout << "Value of variable i is: " << i << endl;
}
return 0;
}
```

```Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
```

2. while statement – The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as -

```while(expression){
statement(s)
}
```

The while statement evaluates expression, which must return a boolean value, If the expression evaluates to true, the while statement executes the statement(s) in the while block.

```
#include <iostream>
using namespace std;

int main()
{
float number, sum = 0;

do {
cout << "Enter a number: ";
cin >> number;
sum += number;
}
while(number != 0);

cout << "Total sum = " << sum;

return 0;
}
```

Output:

```Enter a number: 43
Enter a number: 2
Enter a number: 5
Enter a number: 10
Enter a number: 0
Total sum = 60

```

3. do - while statement – do - while evaluates its expressions at the bottom of the loop instead of the top. The statements within the doblock are always executed at least once.

```do{
statement(s)
}while(expression);
```
```#include <iostream>
using namespace std;
int main() {

int x = 5;
do {
cout << "X is: " << x << endl;
x = x + 1;
} while (x < 10);
return 0;
}
```

Output:

```X is: 5
X is: 6
X is: 7
X is: 8
X is: 9
```