For Loops
YouTube VideoMost 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
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
Here’s a flowchart showing what a For loop may look like:
In this flowchart, we use the shorthand i : [1, x] by 1
to show that the loop counter i
starts at the value
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
When reading this aloud, we might say i : [1, x]
as “For values of i
from
x
incrementing by
i
from
x
incrementing by
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.