Monday, November 30, 2015

The While and Do-While Loops

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

Doing repetitive tasks can be accomplished with a programming loop. This article will cover the while and do-while loops. They appear in many different programming languages and often follow the same construct.

Let us first consider the while loop. When you need to keep on repeating the sames tasks, you can put those tasks within a while loop and it will execute as long as some condition is true:

while (condition)
{
    // do these statements as long as the condition is true
}

In the while loop, first the condition is checked. The condition is anything that yields a Boolean value (either true or false). If the condition in the while loop is true, then the statements within the braces are executed. Otherwise, the loop terminates.

To determine when the loop terminates, a loop-control variable is often used. For example, it could be a variable that keeps a count. As long as the count matches a certain criteria, then the loop would keep on running. As soon as that condition no longer holds, then the while loop terminates.

Consider the following while construct in C++:

// Declares an integer variable and assigns it the value 1
int n = 1;

while (n <= 10)
{
    cout << "The value of n is " << n << endl;

    // This line is important as it makes sure the loop is not infinite
    n++;
}

The above code will produce the following output:

The value of n is 1
The value of n is 2
The value of n is 3
The value of n is 4
The value of n is 5
The value of n is 6
The value of n is 7
The value of n is 8
The value of n is 9
The value of n is 10

Going through the code, a variable n is declared and assigned the value 1. Then comes the while loop: first the condition is checked -- is 1 less than or equal to 10? Yes, it is. Since the condition is true, the statements within the braces are executed: the current value of n is displayed and then the value of n gets incremented. The increment part is very important. If we did not have that line, then the loop would going on infinitely. Infinite loops are to be avoided at all costs because they never end! The program above makes sure the loop ends by adjusting the variable n accordingly in every loop iteration. The condition -- that n is less than 10 -- will eventually become false and thus the loop will terminate.

Let us a now consider the do-while loop:

do
{
    // do these statements (at least once)
} while (condition);

The do-while loop works just like the while loop, but the statements within the braces get executed at least once. That is, when the program reaches the do-while, it starts executing the block statements right away without check the condition! Then, after executing the statements within the braces for the first time, it checks for the condition within the while parenthesis. If that condition is true, the loop statements get executed again. This pattern will keep on repeating as long as the condition is true. When the condition finally becomes false, then the loop terminates and the program goes on to do other stuff.

Consider this program in C++:

int m = 2;

do
{
    cout << "The value of m is " << m << endl;
    m++;

} while (m < 2);

First, a variable is declared and defined with the integer value 2.

The program hits the do-while construct and starts executing the statements right away: it displays the value of m, which is 2. Then, it increments m (i.e. increases its value by 1). The variable m now holds the value 3. The condition in the while parenthesis is then checked (for the first time) and evaluates to false because 3 < 2 is not true. The loop then terminates right away.

Output:
The value of m is 2

So the do-while loop executes the statements at least once, even if the condition within the while parenthesis is false right from the beginning.

In general, while loops are often used when you do not exactly know how many repetitions you have to make in order to accomplish a task. Loops that you know exactly how many times to iterate are often implemented using a for loop.

Learning the C++ programming language? How about doing it with One Hour a Day.

The If Statement

Starting out with programming? Be sure to check out The Self-Taught Programmer.

The if statement is used to control the flow of a program. It allows you to determine where to go when you hit an "intersection" in a program. The construct below works on multiple programming languages and follows almost the same syntax (especially in C-based languages).

if (condition)
{
    // do these statements
}

The way the if statement works is like this: first, it checks the conditions within parenthesis. That has to be something that yields a Boolean value (either true or false). If the condition within the parenthesis is true, then the statements within the braces are executed. Otherwise, nothing is done.

Now, if you want something to happen in case the if condition fails, then that is when the "else" clause comes in handy:

if (condition)
{
    // do these statements
}
else
{
    // otherwise, do these statements
}

In this case, if the condition is false, then the statements in the else-block get executed. In essence, when all if conditions fail, the else statements get executed.

If you wanted to check for more than one specific condition, you can use an else-if construct:

if (condition)
{
    // do these statements
}
else if (another condition)
{
    // do these other statements
}
else
{
    // otherwise, do these statements
}

Adding an else-if statement will allow for another condition check. That is, if the condition in the very first if statement is false, then the condition of the next else-if statement will be checked. If that condition is true, then the statements in the else-if block get executed. Otherwise, it will proceed to check the next condition (if there is any other else-if). When all the conditions fail, the else statements get executed.

Thus, with the if-elseif-else construct, you can determine multiple paths for your program to take. You can have as many conditions to check as you want. Just add more else-if statements like this:

if (condition)
{
    // do these statements
}
else if (another condition)
{
    // do these other statements
}
else if (yet another condition)
{
    // do these other statements
}
else if (and yet another condition)
{
    // do these other statements
}
else
{
    // otherwise, if all the above conditions fail, do these statements
}

Keep in mind that only one path may be chosen. If the very first if-condition is true, then those statements within the braces get executed AND nothing else. All the other else-ifs and the else get skipped. If the very first if-condition is false, then the condition for the next else-if statement is checked. If the else-if-condition is true, then the statements within that else-if block get executed AND nothing else. If that condition is false, then it will keep on checking for other else-if conditions. If all the else-if conditions fail (that is, yield false), then the statements within the else-block get executed. That is it. You will only reach the else part when all of the previous conditions have failed and there is no other way to go. In a way, the "else" tells your program where to go or what to do in the last resort.

Here is an example of an complete if statement construct, in C++:

// Checks whether a number is between 1 and 100
// If the number is less than 1, it says "too small"
// If the number is greater than 100, it says "too big"

if (number < 1)
{
    cout << "Your number is too small." << endl;
}
else if (number > 100)
{
    cout << "Your number is too big." << endl;
}
else
{
    // Number is between 1 and 100
    cout << "You are in the right range!" << endl;
}

First it checks if the number is less than 1. If that is the case, then it is certainly out of range. Otherwise, the number is greater than or equal to 1. For the second condition, it checks whether the number is greater than 100. If that is true, then the number is out of range. Once the two conditions have been checked and they both fail, then there is no other choice, but to conclude that the number has to be between 1 and 100. In that case, there is not even a need to check for any condition; just using an else clause will do.

In conclusion, the if statement is used to control the flow of a program. It lets your program makes choices on what path to take based on the given conditions. Multiple choices are not allowed in an if statement. Only one path may be chosen.

Want a more in-depth look into computer programming? Check out The Self-Taught Programmer.