Get up to 40 % extra points for free! More info
Save up to 80 % on our Swift e-learning courses. Only this week!

Lesson 6 - Loops in the C++ language

In the previous exercise, Solved tasks for C++ lessons 4-5, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on the `for` loop in C++ instead of a thorough-full lesson? Here it is:

Using a `for` loop to execute code `3` times:

``````{CPP_CONSOLE}
for (int i = 0; i < 3; i++) // runs 3 times in total
{
cout << "Knock" << endl;
}
cout << "Penny!" << endl;
cin.get();
{/CPP_CONSOLE}``````

Accessing the loop control variable each iteration:

``````{CPP_CONSOLE}
for (int i = 1; i <= 10; i++)
cout << i << " "; // prints the current value of the loop control variable
cin.get();
{/CPP_CONSOLE}``````

Nesting loops to work with tabular data:

``````{CPP_CONSOLE}
cout << "Here's a simple multiplication table using nested loops:" << endl;
for (int j = 1; j <= 10; j++)
{
for (int i = 1; i <= 10; i++)
cout << (i * j) << " ";
cout << endl;
}
cin.get();
{/CPP_CONSOLE}``````

Would you like to learn more? A complete lesson on this topic follows.

In the previous tutorial, Solved tasks for C++ lessons 4-5, we learned about conditions in the C++ language. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, we certainly won't write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The `for` loop

This loop has a determined fixed number of steps and contains a control variable, typically an integer, which changes values gradually during the loop. The `for` loop syntax is the following:

`for (variable; condition; command)`
• `variable` is the control variable which is set to an initial value (usually `0`, because in programming, everything starts from zero, never from one). For example: `int i = 0`. In the C++ language, we usually declare the variable directly in the loop and it's accessible only from inside the loop. Of course, you could declare the variable separately above the loop as well.
• `condition` is the condition for executing the next step of the loop. Once it becomes false, the entire loop is terminated. The condition may be, for example, `i < 10`.
• `command` tells us what will happen to our variable on every step, i.e. whether it will have increased or decreased. We use the special `++` and `--` operators for this. Of course, you can use these operators outside the loop as well, they decrease or increase a variable by `1`.

Let's create a simple example. Lots of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without using a loop, would look like this:

``````{CPP_CONSOLE}
cout << "Knock" << endl;
cout << "Knock" << endl;
cout << "Knock" << endl;
cout << "Penny!" << endl;
cin.get();
{/CPP_CONSOLE}``````

However, using loops, we no longer have to copy the same code over and over:

``````{CPP_CONSOLE}
for (int i = 0; i < 3; i++)
{
cout << "Knock" << endl;
}
cout << "Penny!" << endl;
cin.get();
{/CPP_CONSOLE}``````

```Console application
Knock
Knock
Knock
Penny!```

The loop will run through 3 times. At the very beginning, `i` is set to zero, the loop then prints "Knock" and increases `i` by one. It continues in the same way with the values one and two. Once `i` hits three, the condition `i < 3` is no longer true and the loop terminates. Loops have the same rules for omitting curly brackets as conditions. In this case, they may be omitted since the loop contains only one command. Now, we can simply change the value from 3 to 10 in the loop declaration. The command will then execute 10x without writing anything else. Surely, you can see that loops are a very powerful tool.

Now, let's put the variable incrementation to use. We'll print the numbers from one to ten and separate them with spaces. Since we want to write numbers next to each other, we'll write a space instead of `endl` this time:

``````{CPP_CONSOLE}
for (int i = 1; i <= 10; i++)
cout << i << " ";
cin.get();
{/CPP_CONSOLE}``````

We can see that the control variable has a different value after each iteration (an iteration is one step of the loop). Notice that this time, the loop doesn't start from zero because we want the initial value to be `1` and the last one to be `10`. Just keep in mind that in programming, almost everything starts from zero, we'll find out why later.

Now, let's print a simple multiplication table that contains the product of numbers from `1` to `10`. All we need to do is to declare a loop from `1` to `10` and multiply the control variable with the current multiplier. Our might look something like this:

``````{CPP_CONSOLE}
cout << "Here's a simple multiplication table using loops: " << endl;
for (int i = 1; i <= 10; i++)
cout << i << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 2 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 3 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 4 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 5 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 6 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 7 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 8 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 9 << " ";
cout << endl;
for (int i = 1; i <= 10; i++)
cout << i * 10 << " ";
cout << endl;
cin.get();
{/CPP_CONSOLE}``````

```Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100```

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

``````{CPP_CONSOLE}
cout << "Here's a simple multiplication table using nested loops: " << endl;
for (int j = 1; j <= 10; j++)
{
for (int i = 1; i <= 10; i++)
cout << i * j << " ";
cout << endl;
}
cin.get();
{/CPP_CONSOLE}``````

Makes a big difference, doesn't it? Obviously, we can't use `i` in both loops since they are nested and would interfere with each other. The variable `j` of the outer loop goes through the values from `1` to `10`. During each iteration of the loop, another inner loop with the variable `i` is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable `j`. After each time the inner loop terminates it's necessary to break the line, which is done using `cout << endl;`.

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate raise an arbitrary number by an arbitrary exponent:

``````{CPP_CONSOLE}
cout << "Exponent calculator" << endl;
cout << "===================" << endl;
cout << "Enter the base:" << endl;
int a, n; // we can declare both variables on a single line
cin >> a;
cout << "Enter the exponent:" << endl;
cin >> n;

int result = a;
for (int i = 0; i < (n - 1); i++)
result = result * a;

cout << "Result: " << result << endl;
cout << "Thank you for using our exponent calculator";
cin.get(); cin.get();
{/CPP_CONSOLE}``````

I'm sure we all know how powers (exponents) work. However, just to be sure, let me remind you that, e.g. `2^3 = 2 * 2 * 2`. So, we compute `a^n` by multiplying the number `a` by the number `a` `n-1` times. Of course, the result must be stored in a variable. Initially, it'll have a value of `a` and this value will be gradually multiplied during the loop. We can see that our variable `result` in the loop body is accessible. If, however, we were to create a variable in a loop body, it would no longer be accessible after the loop terminates.

```Console application
Exponent calculator
==========================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator```

Now, we know what some practical uses of the `for` loop are. Remember that it has a fixed amount of iterations (there's no workaround for this). We shouldn't modify the control variable from inside the loop since the program could get stuck in an infinite loop. Here's the last example of what you should not do:

``````{CPP_CONSOLE}
// this code is wrong
for (int i = 1; i <= 10; i++)
i = 1;
{/CPP_CONSOLE}``````

Ouch, as you can clearly see, the program is stuck. The loop always increments the variable `i`, but it is always set back to `1`. Meaning that it never reaches values `> 10` and the loop never ends. We'll stop the program using the "Stop" button in the Visual Studio toolbar.

If course, we can also have multiple variables in the `for` loop, separated by commas. If we want to create them (declare them), they need to be of the same type.

We can also use any other command instead of `i++`, even multiple commands separated by commas.

So the following code is correct as well and there will be the 10th power of `2` in the `f` variable when the loop finishes.

```int i;
float f;
for (i = 0, f = 1; i < 10; f *= 2, i++) ;```

If we wanted to create the variables in the loop's declaration, they have to be of the same type:

`for (int i = 0, f = 1; i < 10; f *= 2, i++) ;`

We'll go over another loop types in the next lesson, Loops in the C++ language (while, do while).

Download

Downloaded 1x (255.79 kB)
Application includes source codes in language C++

Article has been written for you by David Capka
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
The author learned IT at the Unicorn University - a prestigious college providing education on IT and economics.

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!