For Loop

Basic Loops

For Loop

🙋 Need help? Ask an expert now!

The for loop loops through a block of statements for a specific number of times depending on the loop expression. A typical for loop syntax consists of an initialization statement, a test expression (evaluated to true or false), an update statement as well a code block. The syntax for a for loop looks like this:

for (initialization; test; update) {

The initialization expression is executed only once, just before the loop is entered as if it was outside the loop. It is usually used to declare a counter variable that will be used in the for loop. The test expression is evaluated before each iteration of the loop. If the test expression evaluates to true, the statements inside the loop body is executed. If the test expression evaluates to false, the loop exited. The update expression is executed after each iteration of the loop is completed to update the counter value.

The for loop shown above is a simple loop that prints the numbers 1 through 10. The initialization statement counter = 1 creates a local variable counter that controls the number of times the for loop executes the code block. The test expression counter < 11 is the boolean expression that determines whether or not the for loop is run or exited. The update expression counter++ is crucial as it increases the value of counter by 1 each time the loop is executed. If the update expression did not exist, the for loop would be an infinite loop that keeps printing 1. In most cases, using a for loop and a while loop doesn't make a difference, so you can select the one you are more comfortable with using.

Edit Me on GitHub!

Application Question

Consider the following code segment:

for (num = 0; num < 20; num += 2){
    if (num % 3 == 1){

What numbers are printed to the console after executing the code above?