Sunday 24 September 2017

Iteration Statement- For Loop

Iteration is a process where a set of instruction or statement is executed repeatedly for a specified number of time or until a condition is met.Iteration statements are commonly known as loops.There are three types of looping statements in C++:

A looping is consist of three parts:- initialization, test expression, increment/decrement or update value. A loop will run whenever the test condition is not met if the test condition is met then the loop will break and show the result on the screen.

For loop is most commonly used looping technique because in for loop all three parts of the loop: initialization, test expression, increment/decrement or update value in the same line.

Syntax:
for(intialization;test expression;increment/decrement)

{
 
 //body of loop
 
}
In the above syntax, you will see three parts of the loop in the same line and the three parts are separated by the semicolon, not by the comma's.

Program to print 1 to 10 number by using for loop:
#include<iostream>
using namespace std;
int main(){
 int i;
 cout<<"numbers from 1 to 10"<<endl;
 for(i=1;i<=10;i++){
  cout<<i<<endl;
  
 }
 return 0;
}
Output:
numbers from 1 to 10
1
2
3
4
5
6
7 
8
9
10

Now, let understand how for loop works? Here we have the initial value of i as 1(initialization).The test condition is i<=10 and update expression is i++.
In the beginning, the control goes to the initial condition and assigns the value 1 to i. Now its check whether 1<=10, if the condition is true then the body of the loop will execute and give an increment to i and assign the value 2 to i. Again its check whether 2<=10, if the condition is true then the body of the loop will execute. The whole process will run whenever the test condition is not met. When i becomes equal to 11, the condition i<=10 becomes false and the loop terminates and the program ends.


0 comments:

Post a Comment