Simplifying control structures in C++ Part 2

This article continues on with control structures in C++. Read Part 1 of Control structures here. Part 2 talks about Iteration statements. If you have no idea what a control structure is, read about the basic concept of control structures in all programming languages. 

The for loop

A for loop is an iteration statement that has been designed in C++ to repeat a number of times. The loop repeats while the condition is true and the loop breaks when the condition is false. For loops can be useful for counter variables as they support setting variables at the start and increasing the value before the loop begins.

for loop noteloop diagram

#include <iostream>

using namespace std;

int main()
{
 int j = 1;

 while(j <= 3)
 {
 cout << j << ", ";
 j++;
 }

 cout << "GO\n";
}

</pre>
The for loop code is a program that counts from zero to three, then outputs "GO" when the loop has completed.

<strong>While loop</strong>

The while loop just repeats code while the condition is true. When the condition is no longer true, the loop will stop running. The general form of a while loop is
while(condition)
{
statement;
}

<a href="http://cppbetterexplained.com/wp-content/uploads/2015/05/while-loop.png"><img class="aligncenter size-full wp-image-544" src="http://cppbetterexplained.com/wp-content/uploads/2015/05/while-loop.png" alt="while loop" width="462" height="388" /></a>The while loop code below is a rewrite of the previous for loop program which would count from one to three then display "GO". Instead of using a for loop, we are using a while loop here.
<pre>1
#include <iostream>

using namespace std;

int main()
{
 int j = 1;

 while(j <= 3)
 {
 cout << j << ", ";
 j++;
 }

 cout << "GO\n";
}

The do-while loop

The do while loop is similar to the while loop as it acts like a while loop but the condition is evaluated after the loop begins instead of before. The do while loop is always guaranteed to be executed at least once when it is used.

do while loopdo while loop flowchart

The do while sample code is a program where you type in a number and it will keep running until you type in the number 1.

#include <iostream>
using namespace std;

int main()
{
 int numberinput;

 do 
 {
 cout << "Enter in a number\n";
 cout << "\nIf you enter the number 1, the program will end\n";

 cin >> numberinput;
 }

 while(numberinput != 1);
 // The program will end if number 1 is inputted
}
Share this post