Loops: Part 1

Loops are used when we want a set of statements to execute until certain condition is satisfied or fulfilled. Loops can also be used when we want to take many inputs from the user.

A while loop executes a block of statements as long as the condition remain true. The syntax of a while loop is:


while (condition) {
statements;
}

A while loop runs until the condition becomes false.

For example: If we want to print table of a number. We can manually write all the multiplication but there is a better way, we can use while loop.


#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i<=10) //Condition
{
cout<<2*i<<endl;
i = i+1; //Controlling statement
}
}

The output of this code will be:

2
4
6
8
10
12
14
16
18
20

The controlling statement is very important while writing loops. Without it the loop will run forever. We need our program to move towards the condition statement so that it can be terminated after our work is completed.

In the above example the value of i increases and finally the loop terminates when the value of i becomes greater than 10. We can increase or decrease the value of i according to our condition.

The statement i = i+1 can also be written as i += 1, it works for all the other operators too:
i += 8; //equivalent to i = i+4
i -= 2; //equivalent to i = i-2
i *= 4; //equivalent to i = i*4
i /= 6; //equivalent to i = i/6

Increment Operator

An increment operator is used to increase or decrease the value by 1 and is a commonly used C++ operator.

x++ //equivalent to x = x+1

For example:

int x = 10;
x++;
cout<<x;
// Outputs 11

There are two types of increment operators:

  • Prefix increases the value of, and then carry out the operation.
  • Postfix evaluates the operation and then increases the value

Prefix example:

int x = 10;
int y = ++x;
// x is 11 and y is 11

Postfix example:

int x = 10;
int y = x++;
// x is 11 and y is 10
//First the value of y is made equal to x
//then the value of x is increased.

– -X and X- – works in the same way.

There are two more types of loop. We will look at them in the lesson. Please post your valuable comments and doubts in the comments section. Goodbye.

 

Leave a comment