For Loops

YouTube Video

Video Materials

Most programming languages also support another type of looping construct, known as a For loop. A For loop usually includes an explicitly defined loop counter , a loop condition and loop counter incrementor as part of the loop definition, and is usually used to make sure that a loop only runs a set number of times. This is especially handy for instances where we need to accept exactly $ 5 $ inputs, or if the program should perform a calculation exactly $ 10 $ times.

Many programming languages support a variety of different ways to define how the loop counter in a For loop functions. For these examples, we’ll use a simple definition for the loop counter where it is just an integer that begins at one value and increments by $ 1 $ (the loop counter incrementor) each time until it reaches a second value (the loop condition).

Here’s a flowchart showing what a For loop may look like:

For Loop Flowchart For Loop Flowchart

In this flowchart, we use the shorthand i : [1, x] by 1 to show that the loop counter i starts at the value $ 1 $, and then each loop it is incremented by $ 1 $ until it is larger than x. So, if x = 6, the loop counter i will have the values 1, 2, 3, 4, 5, and 6, and the loop will run exactly $ 6 $ times.

When reading this aloud, we might say i : [1, x] as “For values of i from $ 1 $ through x incrementing by $ 1 $. So, we could say this whole loop is “For values of i from $ 1 $ through x incrementing by $ 1 $, print i.” That should exactly match the original problem statement given earlier:

Write a program that accepts any positive integer as input, and then prints all integers starting with 1 up to the given number.

In code, there are many different ways that For loops are usually defined. We’ll learn how our programming language implements these loops later in this chapter.

Subsections of For Loops