Conditionals and loops in C++

1. Introduction

The thing a computer is particularly good at, especially compared to humans, is repetitive calculation. The computer does not get bored or make mistakes in the way a human might, and it works very fast, so repetitive calculations are not a problem for a computer.

Pitfall. To instruct the computer to do some repetitive calculation you should not simply repeat some of the lines of your program.

This repetition of lines is a basic programming error ("programming by copy and paste") that many beginners fall for (and, sadly, many experts also fall for). It always leads to serious problems or bugs eventually. (The main one being that if you need to change something later it can hard to spot which lines to change.)

Unfortunately many computer systems are badly designed or badly thought out and encourage the "programming by copy and paste" error. Some software companies think a computer is simply a device that sits on a desk that waits for a human to give it repetitive instructions using a mouse. You almost certainly will be able to think of examples straight away. If the human user wants something done twice, then they must click the mouse twice in the same way. All this can be very sad and frustrating...

Historically poor systems like this usually come about because the software company puts much more emphasis on their own profit than on useability. Or it might be that the system itself is so badly designed at the coding level that this is all it can reasonably do without spending a huge amount of time and effort to fix it. Unfortunately, so many people use systems like this today that there is a general misconception that all a general purpose computer like a PC can do is respond to mouse clicks and the keyboard in different ways. This might be great for software companies who want to get rich quick, but is bad for everyone else who have somehow been hoodwinked into thinking that there is no way round the problem. You should not ever have to put up with such a system.

C++ is a very good system in these regards. You should never (or almost never) have to write two identical sets of lines in C++. You shouldn't even have to write two similar sets of lines. If you do find yourself doing this, warning bells should be going off in your head because it indicates a problem with the design of your program, places where it can be improved, and possible issues or bugs later on.

The main techniques in C++ for avoiding repetition in your program text (but at the same time telling the computer to do something repetitively) are loops and functions. This web page gives more details on the simplest cases of the main C++ constructs for looping. Even more details are presented later.

2. While loops in C++

The first, and simplest kind of loop, is that of the while statement. This looks like,

while (<boolean-expression>) {
  <instructions>
}

(Of course <boolean-expression> and <instructions> are not part of C++ but just indicate where you are supposed to put that part of your code.)

The computer carries this out as follows.

You will note that the loop <instructions> in "while" statements are sometimes not done at all, or they may be done out finitely many times and then the computer moves on, or the <boolean-expression> might always compute to true and the while loop is executed for ever.

The C++ type bool is a type just like int or double except that the only values are true or false. We will look at this in more detail later.

To stop a computer program that is "stuck in a loop", press "control-C" at the keyboard.

Remark.

It is common in C++ to declare variables in the <instructions> part of a while statement. These are only in scope ("visible") in the while statement itself, and are not available to the program when the while statement has finished. It is not so common, but it is possible, to declare variables in the (<boolean-expression>) part, and exactly the same applies.

Example.

The following code counts to 100 (and does so properly, starting at 0). It uses a while loop. Try it out!

// whileto100.cpp (click here to download)

#include <iostream>

using namespace std;

int main() {

  int n = 0;
  while (n<100) {
    cout << n << " ";
    n++;
  }
  cout << endl;
  return 0;

}

3. For loops in C++

Next we have the for statement. This can be quite complicated, but in the two most familiar cases looks either like,

for (int n=0; n<test; n++) {
  <instructions>
}

or

for (int n=first-1; n>=0; n--) {
  <instructions>
} 

Note the exact syntax here, and in particular the use of ; and don't use commas instead. In both cases, the code above declares an int variable which is used to "count". (The variable here is called n. It could be called anything you like.) It is in scope ("visible") throughout the <instructions> but not after the final } of the "for" statement. (It also prevents any other variable n outside being accessible.) The use of int variables in for loops like this is typical, and doing for with double variables is not recommended for beginners, though there are other possibilities if you know what you are doing.

In the first case the variable n is given the values 0,1,...,test-1 in that order and for each such value the instructions <instructions> are carried out. In the second case the variable n is given the values first-1,...,1,0 and for each such value the instructions <instructions> are carried out.

Pitfall. Get used to doing for loops with int variables. Problems can occur if you use double variables instead.

These two forms of for are the recommended ones. (In particular, all good programmers get used to counting to 10 "properly" as 0,1,2,3,4,5,6,7,8,9 and do not use the kindergarten method where you start with "one".) However, a more general form is,

for (<start>; <test>; <eachtime>) {
  <instructions>
}

which is roughly equivalent to

<start>;
while (<test>) {
  <instructions>;
  <eachtime>;
}

The equivalence is almost exact: the main difference is that variables declared in <start> (such as n in for (int n=0; n<test; n++)) are local to the loop only and not visible in the rest of the program.

Example.

The following code counts to 100 like the previous example, but uses for.

// countto100.cpp (click here to download)

#include <iostream>

using namespace std;

int main() {

  for (int n=0; n<100; n++) {
    cout << n << " ";
  }
  cout << endl;
  return 0;

}

4. If statements in C++

The if statement is not looping at all, but is so similar in syntax (and is commonly used to control loops) that we cover it here. The two most familiar cases looks either like,

if (<test>) {
  <instructions>
}

and

if (<test>) {
  <instructions-if-true>
} else {
  <instructions-if-false>
}

Beginners should use this format and this indentation exactly. Not doing so could cause confusion or bugs or both. In both cases <test> is an expression to give a true/false bool value (just like for while). In the first case, the <instructions> are carried out once if the value is true and skipped otherwise. In the second case, the <instructions-if-true> are carried out once if the value is true and <instructions-if-false> are carried out once if the value is false. The other instructions are skipped.

Example.

The following is a variation of "think of a number" but tests to see if the number is even or odd, using the % and == operators.

// evenodd.cpp (click here to download)

// This program illustrates cin
#include <iostream>

using namespace std;

int main() {
  int n;
  cout << "Please think of a number." << endl;
  cout << "What is your number?" << endl;
  cin >> n;
  if (n%2==0) { 
    cout << "The number you thought of was even" << endl;
  } else {
    cout << "The number you thought of was odd" << endl;
  } 
  return 0;
}