Friday, 23 December 2011

Episode 11 : for loop

for  loop

In our program,  we need to execute one or more statement for more time.  If we write one statement in many time for many time execute then our code is long and so boring. For easy this operation we use this “for loop”.

Structure of for loop :

for ( initialize ; condition ; increment / decrement)
{
Statement 1 ;
-------------------
Statement n ;
}

When we execute one statement in a particular time , normally we need a variable.  In for loop, we also need a variable and this variable is called control variable.

One for loop has several parts is below :

·       Initialize :  In this part, we declare the control variable to normally  1 or 0.
·       Condition : In this part, we use the conditional expression.  Compiler run the for loop until  value of conditional expression is false or 0.
·       Increment or Decrement : Until the value of conditional expression is false or 0 , the value of the variable is increasing or decreasing one by one. .
·       Statement : Until the conditional expression value is 0, the statement is executed . Here simple or compound statement both are contained. These statement is inside the second bracket ‘{}’.

Caution : Always put semicolon in end of parts of for loop. 

Example :

#include <stdio.h>
void main()
{
int a ;
printf(“Running for loop : \n”)
for ( a = 0 ; a<3 ; a++)
{
printf(“INNOVATION it’s Shojib’s Blog \n %d”,a);
}
}
Output :
Running for loop :
INNOVATION it’s Shojib’s Blog 0
INNOVATION it’s Shojib’s Blog 1
INNOVATION it’s Shojib’s Blog 2


We write a program to execute the printf() function in three time. At first we initialize the control variable is 0, condition is the value of a is less then 3 and  next we increasing the value one by one to use increasing operator and the printf() function is our statement. When we run this program, the compiler look at the initialize point then the condition and compare with these two part and look the increasing part, if the condition is right then the compiler execute the printf() function. After executing one time compiler come back to the initializing point and increase one to the initialized value and now initialize value is 1 then compare with condition and execute the printf () function. Until the condition is false, this process is continue . Finally we found our output is printf() function execute in three times.

Written by “Shojib”

No comments:

Post a Comment