Counter-controlled Loops

Learn about fixed iteration loops, which have a large number of iterations with different intervals.

The for loop

The counter-controlled loop is used to generate a sequence of values. This loop has four parts after the for keyword as shown below:

for (initialization; condition; update) {
    // body of the loop 
}

The initialization value initializes the counter and is executed only once. The condition value checks the value of the counter at the start of each iteration before entering the body of the loop. If it’s true, the body of the for loop is executed, and if false, the for loop is terminated. The update value updates the value of the counter and again checks the condition. We use the semicolon (;) only at the end of the first two parts and enclose these parts in ( and ). We don’t use a semicolon after ) and {. The body of the loop is a set of statements to be repeated.

Note: If there is only one statement in the body of the loop, then curly braces { and } are not needed.

Let’s say we want to produce a program that counts from 00 to 44. We can do this using the for loop as follows:

Get hands-on with 1400+ tech skills courses.