Control structures and operators

Like Python, also C++ has control structures for selection and iteration. We will first compare if and while structures of these languages. After that we see one way to use for loop in C++. Finally, we will briefly introduce C++ operators.

Python vs. C++: selection and loops (if and while)

Let’s compare the selection and loop structures of Python and C++ by considering the following example programs:

def main():
    secret_number = int(input("Input a secret number: "))
    guessed_number = -1
    guesses = 0

    while secret_number != guessed_number:
        guessed_number = int(input("Give a guess: "))

        guesses += 1

        if guessed_number < secret_number:
            print("Your guess is too small!")
        elif guessed_number > secret_number:
            print("Your guess is too great!")
        else:
            print("Correct!")

    print("Number of guesses: ", guesses)

main()
#include <iostream>

using namespace std;

int main() {
    int secret_number = 0;
    cout << "Input a secret number: ";
    cin >> secret_number;

    int guessed_number = -1;
    int guesses = 0;

    while ( secret_number != guessed_number ) {
        cout << "Give a guess: ";
        cin >> guessed_number;

        guesses += 1;

        if ( guessed_number < secret_number ) {
            cout << "Your guess is too small!" << endl;
        } else if (guessed_number > secret_number ) {
            cout << "Your guess is too great!" << endl;
        } else {
            cout << "Correct!" << endl;
        }
    }

    cout << "Number of guesses: "
         << guesses << endl;
}

Without syntactic variance (semicolons, parenthesis etc.) the examples have no differencies. Based on this, we can see what is meant by the claim that programming is a language-independent skill. For example, iteration is a concept that keeps the same from programming language to another.

Let’s pay some attention to use of parenthesis. In C++, you can drop the curly brackets away, if the block has only a single command. For example, the following code

int = 0;
while(i < 10)
{
    ++i;
}
cout << i << endl;

can be shortened as

int = 0;
while(i < 10)
    ++i;
cout << i << endl;

This may seem to be natty, but before you get used to write code following the latest example, you should note that such a programming style can lead to programming errors that are hard to detect. When writing Python code, you have got used to think that indented text belongs inside a block, and thus, you may easily forget the parenthesis. C++ compiler does not mind about missing parenthesis in the following kind of example:

int = 0;
while(i < 10)
    ++i;
    cout << i << endl;
cout << "Job continues after the loop" << endl;

The first cout statement will not be repeated, because it does not belong to the while block. Since the curly brackets are missing, the block consist of a single statement, which in this case is ++i;. The first cout statement is executed only once: at the moment when the iteration ends and the next statement after the iteration is executed.

C++ compiler does not care how you have divided the program text into lines. Two most used ways to position the curly brackets are as follows. The first one of them leads to smaller number of lines:

if( x ) {
    ...
}

The other way has the same indentation for the beginning and ending brackets:

if( x )
{
    ...
}

You can use either of these ways, but it is better to be consistent, especially when concerning control structures. Do not mix the style in the same program.

Caution

In Python programming you may have used exception mechanism (try structure) for example in the place of if statement. Unless you are absolutely sure that you can, then do not try to use exceptions of C++ on this course. Their proper use will be explained only on the next programming course.

For statement in C++ (one way of use)

C++ also has a for loop that has several ways to use. It is especially handful for going through the elements of a data structure. Therefore, we will introduce such usages only when we have learned to use data structures of C++.

To enable you to use for loop already in the exercises of this round, we show how to use it in going through a certain interval of integers:

for ( int number = 5; number < 10; ++number ) {
    cout << 9 * number << endl;
}

The above code corresponds to the following Python code:

for number in range(5, 10):
    print(9 * number)

Terminating a loop

Execution of a loop terminates, when the given condition becomes false. C++ other options to adjust loop execution. Statement

break;

terminates the loop and starts to execute the statement immediately after the loop. If the above statement is written in an inner loop of nested loops, only the execution of the inner loop terminates, but the execution of the outer loop continues.

Statement

continue;

skips the rest of the statements inside the loop and jumps in the beginning of the loop (assuming that the loop condition is still true).

Statement

return;

terminates the whole function and returns to the code after the function call. So, if you write the statement inside a loop, also the loop terminates. Note that the statement can be written in the above form also in a void function. On the other hand, if a function has a return value, a value should also be returned, and you cannot write the statement purely as above. (Functions will be considered more precisely a bit later.)

About C++ operators

The conditions (truth-valued expressions) of previous examples showed some relational operators of C++. In all, C++ has the following relational operators: ==, !=, <, <=, >, and >=, the meaning of which is the same as Python has for the corresponding operators. Like Python, C++ has assignment operators: +=, -=, *=, and /=.

The examples show also the increment operator ++ of C++. For instance, ++i increments the value of the variable i by one. In the same way, the decrement operator -- decrements the value of a variable by one. To be on the safe side, use these operators only as a single operator in an expression. If you combine them with other operators, the result can easily be something you did not expect.

C++ has (of course) normal arithmetic operators for addition, subtraction, multiplication, and division. The operator % means remainder (of an integer). For integers, / means integer division, for example, 7 / 3 = 2 and 1 / 5 = 0.

As logical operators, C++ has the following:

  • logical not: not a, which is the same as !a
  • logical and: a and b, which is the same as a && b
  • logical or: a or b, which is the same as a || b.

The two last ones are so called short-circuit operators, which means that the second operand will not be evaluated, if the result of the whole expression can be concluded based on the first operand. For example, false and a is false, regardless of the value of a. Similarly, true or a is true, regardless of the value of a.

Moreover, the two last logical operators have their bitwise counterparts, i.e. the operators & and |. These operators compare the operands bitwise, i.e. the corresponding binary numbers, bit by bit. C++ also has a bitwise operator ^ for logical xor, i.e. exclusive or. There is no need to use bitwise operators on this course.

C++ has no operator for exponentiation.