Here we will look how we can use the for loop. This tutorial will help you understand for loops from the basics.
What is for loop ?
For loop is the control flow statement. It helps us repeat a block of code specified number of times.
for loop is entry controlled loop, meaning the condition is evaluated before the body is executed.
Let us look at the syntax of for loop.
The above example prints the “learning loops.” 10 times. We will look at other examples below.
Explaining for loop syntax
Let me break down the syntax of for loop.
i is the variable and it contains the value
0 initially. So,
i = 0;is the variable declaration
i < 10;is the exit control condition; the loop will continue till
iis less than
i++;is the increment block.
In the above list, After incrementing the value the loop evaluates the exit condition, and the repetition continues.
But the variable declaration ( i.e.
i = 0; ) is done only once.
Sum of all numbers from 1 to 100
To calculate the sum of all numbers from 1 to 100 we can simply run the code below.
i <= 100 will be true till
i‘s value is less than or equal to
Calculating factorial of 12
Let us see how we can calculate the factorial of 12
If you don’t know what a factorial is, google can be of great help.
Sometimes we might want to do something continuously. That is where infinite loop comes in. You might not find the everyday use case for this loop.
But for now here is the syntax.
In the code above the condition (
i > -1 ) is always true. And we have learned from above that the loop will continue to run until it is false.
Hence, the loop will continue forever.