Lesson 4: Loops: while() and for()

Never get stuck in an infinite loop!
Sisyphus

Practical Programming

The next C/C++ language construct we will discuss is a loop. A loop is used to instruct the computer to execute the same block of code multiple time. The most simple form of a loop is a while() loop – repeat the code block until the loop condition is met. The following example will keep asking the user to enter a positive number until user does so:

int x = 0;
while(x <= 0) {
    cout << “Enter a number: “;
    cin >> x;
}
cout << “Thank you! “ << x << endl;

The program will be executed as follows:

Executed line of code Value of x Comments
int x = 0;
0
while(x <= 0) {
0
(x <= 0) is true, go in the loop
    cout << “Enter a number: “;
0
Print message “Enter a number:”
    cint >> x;
-5
Let’s assume user enters -5
}
-5
Go back to the loop condition
while(x <= 0) {
-5
(x <= 0) is true, go in the loop
    cout << “Enter a number: “;
-5
Print message “Enter a number:”
    cint >> x;
3
Let’s assume user enters 3
}
3
Go back to the loop condition
while(x <= 0) {
3
(x <= 0) is false, exit in the loop
cout << “Thank you! “ << x << endl;
3
Print message “Thank you!”

Run this program in the Visual Studio debugger and enter different numbers. Note that we don’t know how many times the loop will be executed! It all depends on the numbers user enters.

Let’s look at another example that prints all the numbers between 0 and x:

int ii;
int x;
cin >> x;
ii = 0;
while(ii < x) {
    cout << ii << endl;
    ii = ii + 1;
}
cout << “Done” << endl;

If user enters x equal to 3, then the program will be executed as follows:

Executed line of code Value of ii Value of x Comments
cin >> x; Undefined
3
We assume that user enters 3
ii = 0;
0
3
while(ii < x) {
0
3
(ii < x) is true, go in the loop
    cout << ii << endl;
0
3
Print “0″
    ii = ii + 1;
1
3
}
1
3
Go back to the loop condition
while(ii < x) {
1
3
(ii < x) is true, go in the loop
    cout << ii << endl;
1
3
Print “1″
    ii = ii + 1;
2
3
}
2
3
Go back to the loop condition
while(ii < x) {
2
3
(ii < x) is true, go in the loop
    cout << ii << endl;
2
3
Print “2″
    ii = ii + 1;
3
3
}
3
3
Go back to the loop condition
while(ii < x) {
3
3
(ii < x) is false, exit the loop
cout << “Done” << endl;
3
3
Print message  “Done”

Try this program in Visual Studio and use the step-by-step debugger to follow the program execution. Remember to open variables watch window and see how the variables ii and x change on each step.

The previous example with a control variable ii that changes on every step is so common that C/C++ language has a special for() loop construct designed for it! This is how this example can be re-written with the for() loop:

int ii;
int x;
cin >> x;
for(ii = 0; ii < x; ii = ii + 1) {
    cout << ii << endl;
}
cout << “Done” << endl;

The for() loop has the 3 pieces together at the top:

  • control variable initialization: ii = 0
  • loop condition: ii < x
  • control variable update: ii = ii + 1

Any for() loop can be rewritten as a while() loop:

for(initialization; condition; update) {
    loop body;
}

is the same as

initialization;
while(condition) {
    loop body;
    update;
}

And any while() loop can be rewritten as a for() loop by simply having empty initialization and update sections:

while(condition) {
   loop body;
}

is the same as

for( ; condition; ) {
    loop body;
}

To make code more readable, use for() loops when you have a control variable that you need to update on every loop execution and that you check to determine if it is time to exit the loop. Use while() loop in other cases.

You can combine and nest if(), if/else and loops together. Don’t forget curly brackets {} to indicate the boundaries of a code block and indentation to make code readable:

int x;
int ii, jj;
cin >> x;
for(ii = 0; ii < x; ii = ii + 1) {
    if(ii % 2 == 1) {
        for(jj = 0; jj < ii; jj = jj + 1) {
            if(jj % 2 == 1) {
                cout << jj;
            }
        }
        cout << endl;
    }
}

What does the following program do? Try it in Visual Studio and use debugger to see what’s going on!

One common mistake with using loops is writing an infinite loop that never ends. For example, this loop has a condition that is always true (variable ii does not change in the loop body!) and it will print zillions of the same messages on the screen:

int ii = 0;
while(ii < 10) {
   cout << “This is an infinite loop!” << endl;
}

To stop a program in an infinite loop, put focus in the program’s screen and press Ctrl+C . If this doesn’t help, open Task Manager (press Ctrl+Alt+Del), select the program process from the list and press “End Process” button.

Exercises

1) Read a number n from user and print all the even numbers between 0 and n.
2) Read a number n from user and calculate factorial n! = 1*2*3*….*n For example:

0! = 1
1! = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
4! = 1*2*3*4 = 24
...

3) Read a number n from user and calculate Fibonacci number a(n) where

a(0) = 0
a(1) = 1
a(2) = a(1) + a(0) = 0 + 1 = 1
a(3) = a(2) + a(1) = 1 + 1 = 2
a(4) = a(3) + a(2) = 2 + 1 = 3
a(5) = a(4) + a(3) = 3 + 2 = 5
...
a(n) = a(n-1) + a(n-2)

4) Read two numbers a and b from user and calculate divider a / b and reminder a % b by using only addition and subtraction.
6) Read two numbers a and b from user and calculate greatest common divisor for these two numbers using Euclid’s algorithm.
7) Read a positive number n from user and print all positive integer numbers (x, y) such as x*x + y*y < n.

Posted in Practical Programming | 1 Comment

Lesson 3: Conditional Execution and Debugging

If all else fails
English Idiom

Practical Programming

So far all our programs had only one execution path: the program statements were always executed one after another exactly in the order they were written. Today we are going to learn how to enable computer to make decisions and execute different code paths depending on user input, results of calculations, etc.

The simple C/C++ language if() construct allows a code to be executed only when the condition is me. For example, the following code will print a message on the screen only when user enters zero:

int x;
in >> x;
if(x == 0) {
    // this will be executed only when user enters zero
    cout << “Good job!” << endl;
    cout << “You’ve entered zero!” << endl;
}

Note the curly brackets { } around the block of code that will be executed when the condition is met. They are required because you might have multiple statements in this block (as we do in the example above). Without the brackets, the compiler will not know where this block of code ends.

The if() statements can be nested. Good programmers use indentation for each if() “level”  to make the code more readable. Both tabs and spaces can be used for indentation:

if(x == 0) {
    if(y == 0) {
        cout << “Both x and y are zero” << endl;
    }
    if(z == 0) {
        cout << “Both x and z are zero” << endl;
    }
}

The if() condition can be very complex and include logical operators. For example, the code above can be re-written as follows:

if((x == 0) && (y == 0)) {
    cout << “Both x and y are zero” << endl;
}
if((x == 0) && (z == 0)) {
    cout << “Both x and z are zero” << endl;
}

Often, your program needs to execute one piece of code if a condition is true and another piece of code if it is false. You can write two if() statements to achieve this:

int x;
cin >> x;
if(x % 2 == 0) {
    cout << “You’ve entered an even number” << endl;
}
if(x %2 == 1) {
    cout << “You’ve entered an odd number” << endl;
}

Another (simpler and more readable) option is to use if/else language construct:

int x;
cin >> x;
if(x % 2 == 0) {
    cout << “You’ve entered an even number” << endl;
} else {
    cout << “You’ve entered an odd number” << endl;
}

If you have more than two options, you can “chain” if/else together so the “else” part of an if() will be the next if():

int x;
cin >> x;
if(x > 0) {
    cout << “You’ve entered a positive number” << endl;
} else if(x < 0) {
    cout << “You’ve entered a negative number” << endl;
} else {
    cout << “You’ve entered zero” << endl;
}

When you are writing complex programs, it might be hard to understand what exactly the program is doing by reading the code. With a debugger, you can look into the actual program behavior (e.g. will it go into “if” or “else”?), view variables, and even modify variables.

To start the debugger, move cursor to the line within the “main” function and press F9 to set a breakpoint: the debugger stops execution of the program when it gets to the breakpoint. Now you can start debugging by pressing F5. When program stops, you can view or modify values for all variables using “Debug” / “Windows” / “Locals” menu. To continue program execution until next breakpoint press F5; to execute a single line press F10. You can also add “Debug” toolbar to your Visual Studio toolbar (right click on empty space in the toolbar) to have quick access to all debugging commands.

Exercises

1)    Write a program that reads 2 numbers from user and prints the smaller number. For example, if user enters 8 and 4 then the program should print 4.
2)    Write a program that reads 3 integers a,b,c from user and prints the median (the integer in the middle) of the three integers (a,b,c). For example, if user enters 8,10, and 3 then the program should print the median 8.
3)    Write a game of 21: user enters two integers and wins only if the sum of the two integers is equal to 21.

Posted in Practical Programming | 1 Comment

Lesson 2: Variables and Operators

One man’s constant is another man’s variable.
Alan J. Perlis

Practical Programming

A variable is a named space in the computer’s memory that you can write values into or read values from. For example, if you have an integer variable “foo”, you can perform the following operations:

  • Write value 10 into variable “foo”
  • Read value from variable “foo”, the result will be 10
  • Write value 20 into variable “foo”
  • Read value from variable “foo”, the result will be 20

In C/C++ each variable has a name and a type. The variable name must start from a letter and contain only letters, digits and underscore. The variable name must be unique (in the current “scope” – more about this later). The variable type determines how much memory computer needs to allocate for this variable and the kind of data we can store in it. You must always declare the variable (announce its name and type) before you can use it to make sure computer knows what to do:

int foo;             // declare integer variable foo
foo = 10;            // write value 10 into variable foo
cout << foo << endl; // read value from variable foo and
                     // print it on the screen
foo = 20;            // write value 20 into
cout << foo << endl; // read value from variable foo and
                     // print it on the screen

The program fragment above uses comments (start from //) and special variable “cout” from our first lesson. The program prints the two numbers on the screen:

10
20

Create a new project in Visual Studio and try it out! Note that each statement ends with a semicolon ‘;’ that indicates to C/C++ compiler the boundaries of the expression. Don’t forget about them!

Most of the programs process data entered by user. You can read the variable value from the user using another special variable “cin” (full name std::cin) and a special operator >> (note that the input operator >> has a different direction from the output operator <<):

int foo;
cout << “Enter a number: “;  // no << endl because we want user to
                             // enter a number on the same line
cin >> foo;                  // read the user input into variable foo
cout << “You’ve entered “ << foo << endl; // print it back

This program prompts the user to enter a number, reads it from the user and then prints it back to screen.

The C/C++ defines the usual set of mathematical and logical operators: +, -, *, /, % (reminder from dividing one integer by another), < (less), > (greater), <= (less or equal), >= (greater or equal), == (equal) that can be used to calculate variable values. The usual order of operations apply and we use parentheses ‘(‘ and ‘)’ to force the order of operations we need:

int foo;
int bar;
foo = 10;
bar = (foo + 5) * 10 + 1;
cout << bar << endl; // this would print 51

Before reading a value from a variable,  it is important to always write a value into this variable first. If you try to read the value from an uninitialized variable (i.e. a variable you didn’t write before) then you will might get an error and your program might not behave as expected. This is one of the most common programming errors:

int foo;
cout << foo << endl; // this is an error, foo is un-initialized

You can combine a variable declaration with the assignment of the initial value to make sure you have no un-initialized variables:

int foo = 10;
int bar = foo + 5;
cout << foo << endl; // prints 10
cout << bar << endl; // prints 15

There many variable types available in C/C++ languages, the most commonly used are:

Type Values Range in Visual Studio
bool logical, true (1) or false (0) true (1) or false (0)
char characters (e.g. ‘a’) ASCII (0 to 255)
int the integer numbers –2,147,483,648 to 2,147,483,647
unsigned int (or simply unsigned) the integer numbers greater or equal to 0 0 to 4,294,967,295
float the floating point numbers 3.4E +/- 38 (7 digits)
double the floating point numbers with range larger than or equal to the range of type float 1.7E +/- 308 (15 digits)

Using special operator sizeof() you can find out how much memory will be taken by a variable of a given type. Try the following code in Visual Studio to find out how much memory is used by a char type:

cout << “Char type takes “ << sizeof(char) << “ bytes” << endl;

Exercises

1)    Write a program that prints how much memory is taken by each of the types from the table above using the sizeof() operator.
2)    Define 2 integer variables a, b; read their values from the user and print out the average of these two values.
3)    Write a program that exchanges the values of two variables a, b.
4)    (Hard) Write a program that exchanges the values of two variables a, b without using an extra variable.

 

Posted in Practical Programming | 1 Comment