C++ - Chapter 4 - Loops
Introduction
Suppose you are tasked with writing a program that needs to iteratively calculate a value. This could be computing a summation, multiplication tables, compound interest, or an infinite number of other items. You could write a single line of code for every calculation that needs to be made, or you implement the calculation in a loop.
There are three types of loops in C++: the for loop, the while loop, and the do/while loop. Each type has it's own advantages.
The codes below will illustrate the use of each of the types of loops.
Definitions (in layman's terms)
For Loop A loop that continues until an incrementation variable has reached a predefined value.
While Loop A loop that is only executed and continued when (a) specified condition(s) is(are) true.
Do/While Loop A loop that is executed at least once and continues only if (a) specified condition(s) is(are) true.
Code:
#include <iostream>
using namespace std;
int main (void)
{
int x, y;
for (x = 0; x < 5; x++)
{
cout<<"I have looped: "<<x<<" times."<<endl;
}
return 0;
}
Output
I have looped: 0 times. I have looped: 1 times. I have looped: 2 times. I have looped: 3 times. I have looped: 4 times.
Breakdown
A for loop is initialized by the statement: for (x = 0; x < 5; x++). The syntax of this is:
for (initial_value; value_inequality; value_increment)
The statements within the for loop are bracketed, although this is not a requirement for a single statement. In the example above, we could have typed:
for (x = 0; x < 5; x++) cout<<"I have looped: "<<x<<" times."<<endl;
| < Back - Working with Text | Index | Next - Loops > |



