google.com, pub-4617457846989927, DIRECT, f08c47fec0942fa0 Learn to enjoy every minute of your life.Only I can change my life.: for loop - syntax and explaination

Tuesday, April 8, 2014

for loop - syntax and explaination

The for loop :-

Syntax:
                   for (initialization;condition ;increase)
                          {         ---------;
                                    statement;
                           }

and its main function is to repeat statement while condition remains true , like the while loop .
But in addition ,for provides places to specify an initialization instruction and an increase instruction .
The three expression inside for loop have to be separated by semicolon. 
So this loop is specially designed to perform a repetitive action with a counter.

It works the following way :

1. Initialization is executed .Generally it is an initial value setting for a counter variable .This is executed only once.
2. Condition is checked ,if it is true the loop continues, otherwise the loop finishes and statement is skipped.
3. Statement is executed . As usual , it can be either single instruction or a block of instruction enclosed within curly brackets{}.

Different forms of for loop: -
1.  single statement:
for(i=0;i<10;i++)
statement;

2. compound statement:
for(i=0;i<10;i++)
{
         ----------;
         statement;
         ----------;
         ----------;
}

3. loop with no body

for(i=0;i<10;i++)
;
      or
for(i=0;i<10;i++);

4.Multiple initialization and multiple updates separated by comma :-
 for(i=0;j=0;i<10;i++;j++)
statement;

5.for (;i<10;i++)

6.for(;i<10;)

7.for(;;)
statement;

Nesting for statement :-
         One for statement can be written within another for statement .This is called nesting of for statement
for(i=0;i<25;i++)
{
    ------------;
    statement;
      for(j=0;j<10;j++)
         {
                statement;
          }
    ---------;
}
 here for every value of i the inner loop will be executed 10 times.

The for loop is very flexible powerful and most commonly used loop.
It is useful when the number of repetition is known in advanced.

No comments:

Post a Comment

अच्छे विचार करे विचार

  पहचान की नुमाईश, जरा कम करें... जहाँ भी "मैं" लिखा है, उसे "हम" करें... हमारी "इच्छाओं" से ज़्यादा "सुन...