Thursday 17 October 2013

For Loop | For Loop in Programming

for loop c++,  for loop java, for loop vb, for loop matlabfor loop php
for loop vba, for loop oracle
Let’s see what we do in a loop. In a loop, we initialize variable(s) at first. Then we set a condition for the continuation/termination of the loop. To meet the condition to terminate the loop, we affect the condition in the body of the loop. If there is a variable in the condition, the value of that variable is changed within the body of the loop. If the value of the variable is not changed, then the condition of termination of the loop will not meet and loop will become an infinite one. So there are three things in a loop structure i.e. (i) initialization, (ii) a continuation/termination condition and (iii) changing the value of the condition variable, usually the increment of the variable value.
To implement these things, C provides a loop structure known as for loop. This is the most often used structure to perform repetition tasks for a known number of repetitions. The syntax of for loop is given below.
for ( initialization condition ; continuation condition ; incrementing condition )
{
            Statement(s);
}
We see that a ‘for statement’ consists of three parts. In initialization condition, we initialize some variable while in continuation condition, we set a condition for the continuation of the loop. In third part, we increment the value of the variable for which the termination condition is set.

Let’s suppose, we have a variable counter of type int. We write for loop in our program as

for ( counter = 0; counter < 10 ; counter = counter + 1 )
            {
                        cout << counter <<endl;
            }

This ‘for loop’ will print on the screen 0, 1, 2, …, 9 on separate lines ( as use endl in our cout statement). In for loop, at first, we initialize the variable counter to 0. And in the termination condition, we write counter < 10. This means that the loop will continue till value of counter is less than 10. In other words, the loop will terminate statement, we write counter = counter + 1 this means that we add 1 to the existing value of counter. We call it incrementing the variable.

No comments:

Post a Comment