Site icon Learn C++

Learn To Use For Loops In C++

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.

[crayon-6606982087403111237157/]

We can create single-line for() loop as an example here,

[crayon-6606982087409349480872/]

We can define variable in the for() parameters as below.

[crayon-660698208740b843542917/]

or we can dive it to two lines,

[crayon-660698208740d591647435/]

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,

[crayon-660698208740f760096229/]

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

[crayon-6606982087410868108286/]

This code below will print out even numbers between 0 and 10, the output will be 0,2,4,6,8,10

[crayon-6606982087412629622154/]

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,

[crayon-6606982087415775067424/]

This code below will print out odd numbers between 1 and 9, the output will be 1,3,5,7,9

[crayon-6606982087416059102125/]

and as same above we can also write like this too,

[crayon-6606982087418769440721/]

If you want to learn about more advanced usage and General Loop Statements in Modern C++ please check this post,

https://learncplusplus.org/general-loop-statements-in-modern-c/

 

Exit mobile version