C++…Control Structures (Loops)

Lets get into loops today. What a loop does is run the same set of code until the condition is false or meets a condition you choose. So first is the while loop its format is while (expression) statement. Here’s an example:

#include<iostream>
using namespace std;

int main()
{

int x;

cout<<"Enter a number: ";

cin>>x;

while(x>0)
{
cout<<x;
--x;
}
return 0;
}

So when you were to run this program and enter the number 10 it would print out:
10
9
8
7
6
5
4
3
2
1

and stop because x is greater than 0 so it wont print 0 or any negative numbers. As you should know the — means subtract 1 from x and if you were to put ++ that would be to add one. This should be pretty simple to understand.

Now we move into the do-while loop. The format for this one is do statement while (condition). This is simple to grasp if you understood the while loop. Do while is used when you need to determine the end of a loop from within the loop itself. For example lets say your working on a program that makes a database of employees in your company. You want to enter they’re name, age, and weekly pay. You would have your program ask these three questions for each employee once your done you can have your program end when you type something like done in the name section. Here’s a do-while loop example program:

#include
using namespace std;

int main()
{

string name;
do {
cout << "Name: ";
cin >> name;
}
while (name != done);
return0;
}

This was a simple example of a do-while loop. When we get into outputting to files we’ll come back to this example. But for now you can see how you can use a do-while loop. This example asks for a name and will keep asking until you enter “done”.

The last loop we’ll go over today is the for loop. for (initialization; condition; increase) statement; . Lets get right into an example, it should explain itself.

#include
using namespace std;

int main()
{
for (x=100; x != 0; x--){
cout<< x <<endl;
}
cout<<"Done!";
system("pause");
return0;
}

The out put would be:

100
99
98
97
96
95
94...

It will continue to 1 and wont print 0 but once it gets to 0 instead it will print Done!. So as you can see a for loop starting from the initialization will continue to do what your increase(or decrease) until the condition is met. So these are three of the Control Structures you need to know. In future examples we’ll begin to use them more.