In programming, one of the most used statement is for() loops. It is used to count in range with given conditions. If you know exactly how many times you want to execute a block of code in your loop, then they are very useful than other loops. Occasionally, it is used to calculate series in range or to list elements that have the number of elements (i.e. string lists, arrays, char arrays, vectors, structured arrays, etc. )
for() function is generally used with 3 parameters separated by ; character. the first one is initial-expression defines primary start condition (a=0 for example) and the second one is conditional expression defines looping condition ( for example a<10), this condition limits its range, and the third parameter is looping condition that defines the change in our loop statement in every loop.
1 2 3 4 |
for ( initail-expression ; conditional-expression ; loop-expression ) loop statement |
We can create single-line for() loop as an example here,
1 2 3 4 |
int a; for( a=0; a<=10; a++) cout << a << ","; |
We can define variable in the for() parameters as below.
1 2 3 |
for( int a=0; a<=10; a++) cout << a << ","; |
or we can dive it to two lines,
1 2 3 4 |
for( int a=0; a<=10; a++) cout << a << ","; |
these 3 examples above are same. If we have more than one line in our code block, then we must use { and } brackets, as here,
1 2 3 4 5 6 |
for( int a=0; a<=10; a++) { cout << a << ","; } |
Note that in for loops last parameter has no ; character and never put ; at the end of for without statement like this for( i=0; i<10; i++ ); This example below will print out numbers between 0 and 10, including 0 and 10. The output will be 0,1,2,3,4,5,6,7,8,9,10
1 2 3 4 5 6 |
for( int a =0; a<=10; a++) { cout << a << ","; } |
This code below will print out even numbers between 0 and 10, the output will be 0,2,4,6,8,10
1 2 3 4 5 6 |
for ( int a=0; a<=10; a+=2 ) { cout << a << ","; } |
Instead of a+2 term to increase we can use a = a+2 also as here, but remember this is slower than the previous one in operation,
1 2 3 4 5 6 |
for ( int a=0; a<=10; a=a+2 ) { cout << a << ","; } |
This code below will print out odd numbers between 1 and 9, the output will be 1,3,5,7,9
1 2 3 4 5 6 |
for ( int a=1; a<=9; a+=2 ) { cout << a << ","; } |
and as same above we can also write like this too,
1 2 3 4 5 6 |
for ( int a=1; a<=9; a=a+2 ) { cout << a << ","; } |
If you want to learn about more advanced usage and General Loop Statements in Modern C++ please check this post,