Showing posts with label Loops. Show all posts
Showing posts with label Loops. Show all posts

Tuesday, December 1, 2015

The For Loop

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

When you need to perform repeated actions, over and over again, making a programming loop is often the preferred approach. The while and for loops are the most common types of loops. This article will consider the traditional "for" loop, the one derived from the C programming language. Other kinds of for loops are also available, depending on the programming language, and allow you to more conveniently loop over data types such as arrays and objects.

The syntax for the for loop is as follows:

for (initializer; condition; increment/decrement)
{
    // do these statements as long as condition holds true
}

The construct above is often the same for many programming languages. Some programming languages allow you to omit the parenthesis, others need you to place a colon (:) at the end of the first line, and so on. This article will consider the for loop using the C/C++ syntax.

The way the for loop works is it first initializes a certain variable (or variables). Then, it checks the condition to see if it is true. If the condition is true, the statements within the braces are executed. After that, the loop goes on to increment or decrement the loop control variable (which is often the one you had just initialized in the initializer list). Then, it checks for the condition to see if it still holds true. If so, then it goes on to run the statements again. Then it increments or decrements the loop control variable. Then it checks the condition again. This pattern repeats until the condition becomes false, whereupon the loop terminates and the program continues to do whatever it needs to do next.

Let us take a look a concrete example:

for (int i = 1; i <= 10; i++)
{
    cout << i << endl;
}

The above outputs the following:

1
2
3
4
5
6
7
8
9
10

Going the for loop above, first an integer variable named "i" is declared and then initialized with value 1. Then, the condition part is checked. Is 1 <= 10? Yes, it is true, so it executes the statements within the braces. In this case, it only outputs the value of the variable "i." After executing the cout statement, the variable "i" gets incremented: i++, going from value 1 to value 2. After that increment operation, the loop condition is once again checked. If the condition holds true, which it is (2 <= 10), then it goes on to execute the loop statements again. Then i gets incremented, and becomes 3. The condition is again checked (3 <= 10), holds true because the comparison yields a true value. The statements are once again executed, the loop control variable "i" is incremented, the condition is checked. This pattern repeats over and over until the loop condition becomes false, whereupon the loop terminates. In this case, that will be when i becomes 11. So in the end, the loop produces an output that counts from 1 to 10.

For loops are often used to go through the elements of an array:

// An array of integers with 8 elements
int myArray[8] = { 2, 3, 6, 3, 21, 14, 17, 1 };

// To hold the size of the array (i.e. number of elements)
int arraySize = 8;

for (int i = 0; i < arraySize; i++)
{
    cout << myArray[i] << endl;
}

The above outputs all the elements of the array, each in a new line. Note that for arrays, you start counting from 0 and the last element is always the size (or length) of the array minus one. Thus the for loop construct usually follows the format above.

Output:

2
3
6
3
21
14
17
1

In general, the for loop is used when you know specifically how many times to iterate. In the above example, the length of the array was known and it was expected the loop would repeat 8 times. When you do not really know how many times you are going to iterate or you would like some more flexibility and freedom in your loop, you would use a while loop.

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

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.