Contents

Part 1

Chapter 3

Taking off from how sequence works in a computer program we will look at how we can begin to alter the typically sequential flow of control into other structures. The first basic control structure is a selection statement. At its essence, a control structure allows a program to make a choice to run a section of code or not.

When we finished chapter 2, we had an example that added two numbers. It had two problems. We are going to take a look at how we can fix the first of those two problems. The first problem was that the numbers are hard coded into the program and therefore will only ever produce 1 result. We need to look at input to fix this problem. The second problem is that it will only ever add 2 numbers and we need to learn about loops before we can solve that problem.

Input

Earlier we introduced the standard output object, cout. There is a similar standard input object known as cin. By default, cin will read from the keyboard and it will allow you to enter information into your program. We can use this to get data into our program. So we can use cin to read two numbers from the keyboard and add those numbers.

#include <iostream> //this allows us to output

using std::cout;    //this is our standard output
using std::cin;     //this is our standard input
using std::endl;    //this is like \n, the newline character

int main() // our main program
{
    int value1;     //this is our first value
    int value2;     //this is our second value
    int sum;

    cin >> value1;  //this will try to read the first number from the keyboard
    cin >> value2;  //this will try to read the second number from the keyboard

    sum = value1 + value2;  //add value1 and value2 and store the result in sum

    cout << "The sum of " << value1 << " and " << value2 << " is " << sum << endl; //This will print the output line

    return 0;

}

Program 3.1

In program 3.1, we have altered program 2.2 to read in the values using cin. So we should learn a little more about how cin works. cin will try to read as much data that matches the type as it can. So since value1 is an int cin will try to read as many integers as it can. It will stop when either: 1. It reads something that is not a number, e.g. a letter, 2. It "sees" a whitespace character.

A whitespace character is anything that makes a space in our typing, like a space, a newline or a tab. So if someone ran program 3.1 and entered the following input:

10 20

we would get the following output:

The sum of 10 and 20 is 30

We would get the same output if the input was:

10 20

So now we can ask the user for data and read it into our program, we can start to use what they have told us to do and make choices about what we should do.

Selection

Selection is the second main way we organize our programs. A selection statement allows your program to make a decision between a set of alternatives. There are two basic selection statements in C++, the if statement and the switch statement. Selection statements use Boolean expressions to make their choices.

Imagine in our program that adds two numbers, we only want to add the numbers if they are even. We can check to see if a number is even by looking at the remainder of integer division. You recall the % operator, we can use this to find the remainder. Then we can use the keyword if and a boolean expression to decide.

Boolean Expression

A boolean expression is an expression that result in a value of true or false. The expressions can be simple like x > 10 or complex like x > 10 && y < 6 || Z * a == 10. In the simple expression we have just 1 boolean expression. In the complex expression we build up the larger expression from single expressions and join them using boolean conjunctions of and (&&), or (||) and not (!).

Using an and conjunction will result in a value of true if and only if, both expressions are true. For example, I like coffee and I like cookies would be a true expression if and only if you like both coffee and cookies. It would be a false statement if you didn't like either coffee, cookies or if you like neither of them.

Using an or conjunction will result in a value of true if either of the expressions are true. For example, I am learning C++ or I am learning brain surgery. This is true because you are reading this text and therefore learning C++. You might also happen to be learning brain surgery but that doesn't effect the truth of the total expression. An or statement is only false if both statements are false.

A not conjunction simply flips the truth of an expression. It makes a true statement false and a false statement true.

So we could now adjust our program 3.2 to only add the numbers if the numbers are even.

#include <iostream> //this allows us to output

using std::cout;    //this is our standard output
using std::cin;     //this is our standard input
using std::endl;    //this is like \n, the newline character

int main() // our main program
{
    int value1;     //this is our first value
    int value2;     //this is our second value
    int sum;

    cin >> value1;  //this will try to read the first number from the keyboard
    cin >> value2;  //this will try to read the second number from the keyboard

    if ( value1 % 2 == 0 && value2 % 2 == 0 )
    {
        sum = value1 + value2;  //add value1 and value2 and store the result in sum

        cout << "The sum of " << value1 << " and " << value2 << " is " << sum << endl; //This will print the output line
    }
    return 0;

}

Program 3.2

So in program 3.2 we have add the if statement after the cin statements. This statement looks at the remainder of value1 divided by 2 and checks to see if it is 0. It then goes and checks the remainder when value2 is divided by 0. If they are both 0, then it goes ahead and adds them. It does nothing if either one of them is not even. If we leave our program like this then the user might be wondering what's going on, so we should modify this program to let our users know what's going on.

To do this we need to add another branch in case either number isn't even. We use the keyword else to do this.

#include <iostream> //this allows us to output

using std::cout;    //this is our standard output
using std::cin;     //this is our standard input
using std::endl;    //this is like \n, the newline character

int main() // our main program
{
    int value1;     //this is our first value
    int value2;     //this is our second value
    int sum;

    cin >> value1;  //this will try to read the first number from the keyboard
    cin >> value2;  //this will try to read the second number from the keyboard

    if ( value1 % 2 == 0 && value2 % 2 == 0 )
    {
        sum = value1 + value2;  //add value1 and value2 and store the result in sum

        cout << "The sum of " << value1 << " and " << value2 << " is " << sum << endl; //This will print the output line
    }
    else
    {
        cout << "Sorry, one of your numbers wasn't even.  I only add numbers if they are even." << endl;
    }
    return 0;

}

Program 3.3

So in program 3.3, we have added our else branch to handle the case where one of the numbers isn't even. The else branch is optional in C++ and we include it here to give more output to our users. The use of the curly braces { } needs a minute of attention. So the { } group code together in what is called a block. Both the if and the else only control a single line of code unless the lines of code are grouped together in a block. So in the if, we have two lines of code so the { } are needed to group them in a block. In the else branch, there is only 1 line of code and so the { } are not strictly necessary. I always encourage adding them in case you end up adding more lines in the future. That way you won't need to add them later. There are lots of times when I know the if or else will only control 1 line and so I'll leave them off.

Maybe we want to be even better with our output and give our users more information about which number wasn't even. So we can do one more modification to our program to allow for this.

#include <iostream> //this allows us to output

using std::cout;    //this is our standard output
using std::cin;     //this is our standard input
using std::endl;    //this is like \n, the newline character

int main() // our main program
{
    int value1;     //this is our first value
    int value2;     //this is our second value
    int sum;

    cin >> value1;  //this will try to read the first number from the keyboard
    cin >> value2;  //this will try to read the second number from the keyboard

    if ( value1 % 2 == 0 && value2 % 2 == 0 )
    {
        sum = value1 + value2;  //add value1 and value2 and store the result in sum

        cout << "The sum of " << value1 << " and " << value2 << " is " << sum << endl; //This will print the output line
    }
    else if ( value1 % 2 == 0 ) //since value1 % 2 == 0, value1 is even
    {
        cout << "Sorry your number " << value2 << " isn't even.  I only add numbers if they are even." << endl;
    }
    else if ( value2 % 2 == 0 ) // since value2 % 2 == 0, value2 is even
    {
        cout << "Sorry your number " << value1 << " isn't even.  I only add numbers if they are even." << endl;
    }else //if we get here, neither number is even
    {
        cout << "Sorry, your numbers " << value1 << " and " << value2 << " aren't even.  I only add numbers if they are even." << endl;
    }
    return 0;

}

Program 3.4

In program 3.4, I've added two extra if statements to check which value wasn't even. We can add as many of these blocks as we need. Notice that we don't have an boolean expression for our else branch. It serves as the catch all branch if none of the branches before are true.

Switch

C++ has an alternate selection statement. It is useful in certain situations but cannot be applied to all the same problems that an if-else structure can be. The first limitation of a switch statement is that you can only use them when you have integral data types, int, char, long, short and enum. That means you can't switch on a string. That said maybe you gave the users a choice of 5 numbers 1-5 and you wanted to do something based on their input. You could use a program like this one to figure out what they entered.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    int number;

    cout << "Please tell me a number: ";
    cin >> number;
    cout << endl;

    cout << "Your number is ";
    switch( number )
    {
    case 1:
        cout << "not even.";
    break;
    case 2:
        cout << "even.";
    break;
    case 3:
        cout << "not even.";
    break;
    case 4:
        cout << "even.";
    break;
    case 5:
        cout << "not even.";
    break;
    default:
        cout << " not a number between 1 and 5.";
    break;
    }
    return 0;
}

Program 3.5

So in program 3.5 we use a switch statement to look at their number and decide what to displayed based on that number.

Summary

Selection statements are the second way we can structure our programs. The main use of the selection statement is to allow us to decide to run certain blocks of code or not. We can build up very large selection structures to make very complex decisions. We base our decisions on boolean expressions that are statements that in turn produce a true or false value.


Written by: David McPherson © 2019

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

hit counter of smallseotools