Pages

Sunday, May 15, 2011

For Loop (Iteration)

for loop

                Syntax:
                                for(initialization; expression; increment/decrement)
                                                {
                                                //loop body
                                                //what instruction to be executed
                                                }

                This is a unique loop that takes three parameters. The first one is called initialization indicates an initial value. The Second is the expression or usually the condition for the loop. The third one refers to the movement of the data or also known as the increment or the decrement of the said value.

Example 1:

                Display a series of number from 1 to 10 separated by comma (,).

                for(int a = 1; a <= 10; ++a)
                  {
                     cout<<a<<”,”;
                  }

                Notice that the code from the previous loops has 5 or more lines just to do a simple task. In the example code, variable a is declared and at the same time is initialized. Then the program evaluates the condition if true or not. If the condition is true then it will execute the loop body. After each execution of the body, the third parameter is executed and that is variable a is incremented by 1 (by the way, this increment or decrement is not limited by 1). The program will evaluate again if the condition is true and will continue to do this process (evaluate -> if true execute loop body -> inc/dec value) except from the initialization until such time that the condition is no longer true.

Sample Problem 1:
                Modify example 1 such that displays a multiple of 10 from 10 to 100.

                #include<iostream>
                using namespace std;

                int main( )
                {
                  for (int a = 1; a <= 10; ++a)
                    {
                      cout<<(a * 10)<<”,”;
                    }
                return 0;
                }
                In this problem, variable a is multiplied by 10 each time it will be displayed. Please take note that the value of a does not change when applied by multiplication operator (*), it just multiplies the value of variable a by 10.
You can have another solution for this one by this fragment of code:

                                for(int a = 10; a <= 100; a = a + 10)
                                  {
                                    cout<<a<<”,”;
                                  }

                Initialize variable a by 10, change the condition to a <= 100 and increment by 10.

No comments:

Post a Comment