Skip to Content
For Loop Demo


Iterating over a sequence of numbers is so common that C++, like most other programming languages, has a special syntax for it.

When we know exactly how many times we want to iterate (or when we are counting), we can use a for loop instead of a while loop:

for (int i = 0; i < 20; i++) { std::cout << "I will not throw paper airplanes in class.\n"; }

Let’s take a closer look at the first line:

for (int i = 0; i < 20; i++)

There are three separate parts to this separated by ;:

  • The initialization of a counter: int i = 0
  • The continue condition: i < 20
  • The change in the counter (in this case an increment): i++

So here we are creating a variable i that starts from 0. We will repeat the code inside over and over again when i is less than 20. At the end the for loop, we are adding 1 to i using the ++ operator.



Run the code to see the for loop in action!

Folder Icon

Take this course for free

Already have an account?