# The for loop

## 1.  The for loop

Often in programming languages you have to repeat the certain parts of program code. If a number of code repeating is known in advance the most appropriate is to use the loop for. This is the most general sort of a loop and this loop has the following syntax.
 For ( initial_expression ; condtion_of_execution ; term_of_increment) // command_block

Behind the main word for, within the brackets ( ) are cited three groups of commands which are separated by the semicolon sign. The procedure in which the for block is executed is:
1)      Firstly the program calculates the initial_expression. Commonly this is assigning value to a counter which is necessary for controlling the repetition of the loop.
2)      The program calculates the condtion_of_execution, the expression which result must be a bool type (true or false). If the result is false then the program skips the command bloc and the program continues execution form the first command after the for loop block.
3)      If the condtion_of_execution is true than program executes the command_block.
4)      At the end program calculates the term_of_increment. After the calculation program is going back to the beginning of the loop and the loop is repeting form the point 2.
The loop is repeating itself until the condtion_of execution gives logical untruth. After that the program skips the loop and continues for the first command after the for loop block.
Let’s look at the example of the for loop. In this example we will write the program for factorial calculating.
 n! = 1 * 2 * … * (n – 2) * (n – 1) * n
Start the new project and write the following code.
 // For Loop.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) {             int n;             cout << " Enter a real number: ";             cin >> n;             long int f = 1;             for (int i = 1; i <= n; i++)                         f *= i;             cout << n << "! = " << f << endl;             return 0; }
Before the program enters in the loop we have to define the initial value of the variable f in which the program will accumulate product. When the program enters in the loop we need to declare the loop counter, variable  i of the type int and assign the initial value of 2. Inside of a loop we multiply variable f with the loop counter and in the end of the loop body we increase the loop counter. The loop is repeating until the loop counter is smaller or equal to the input number.
Now we will investigate the scenario when we enter a number which is smaller than 2. When the program is executing the loop for the first time it will report an error. The reason for reporting the error is that the condition_of_execution wouldn’t be satisfied and the loop will be skipped. This is correct because 1! = 0. We could write the for loop in this form
 For ( int i = n;  i > 1; i--)        f  *= 1;

It could happen that the condition_of_expression is always satisfied and then the loop will be executed unlimited number of times. The example of this loop is given below.
 // Don’t run this example because it will block your computer. HAHA cout << “Unlimited loop” << endl; for (int i = 5; i > 1; ) cout << “a” ;

Initial expression and expression of growth may consist of more than one expression which are separated by commas. This will enable us to write the factorial program in more concise way.
 // For Loop.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) {             int n;             cout << " Enter a real number: ";             cin >> n;             long f = 1;             int i;             for ( i = 2, f = 1;  i <= n; f *= i, i++) ;             cout << n << "! = " << f << endl;             return 0; }

In the first expression we are setting a loop counter and the variable f to initial value. Command for multiplying with loop counter is transferred behind the command block in the expression_of_growth so now the command block is just empty space. We can’t forget about command block because if we do forget about it the compiler will include the next command into the loop. The declaration of the loop counter is now transferred in front of the for loop because the initial expression doesn’t accept multiple declaration. If we entered the for loop as following:
 for ( int i = 2, long int f = 1;  i <= n; f *= i, i++) ;
than the compiler would report that declaration of variable i is improperly terminated. The reason for this error is that after the comma sign compiler encountered the keyword long.
If the loop for contains declaration variables than the area of variable extends only to the end of the loop. For example:
 #include using namespace std; int main ( ) {       int  i = -1;       for (int i = 1; i <= 10;  i++ )             cout << i << endl;             cout << i << endl;         return 0; }

For loops can only be nested one inside another. For example:
 // Nested for loops.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include using namespace std; int _tmain(int argc, _TCHAR* argv[]) {             for (int l = 1; l <= 100; l++) {                         for (int s = 1; s <= 100; s++)                                    cout << setw(5) << l * s;                         cout << endl;             }             return 0; }
After implementing and running the program, the display will show the product of numbers from 1 to 100.

Upon entering the outer loop, the counter is initialized to the value 1 row and with it goes into a loop. In the inner loop counter columns varies from 1 to 100 and for each value is calculated by multiplying its rows with the counter. Upon completion of the inner loop prints a new line character, which ends with a block of statements outside the loop. Follow increment counter lines and return to the beginning of the external loop. The inner loop is repeated from 1 to 100. As you can see for each value of the counter external loop running the entire inner loop. To obtain print pravilin numbers in columns, in the above example, we used an operator to handle setw (). The argument of this manipulator determine how to predict the smallest space to print the data that follows in the output stream. If the data is shorter than the space provided, the remaining places will be filled with blanks. Manipulator setw () is defined in the file header iomanip.
Blogger Comment