if

Flow of Control in C++

Branching control structures are used when we want the machine to choose an alternative based on a binary true / false assertion. If the statement is true, the computer executes an action. Alternatively, if the statement is false, it may execute a different action. The branching control structure depends on the bool data type; all branching statements are conditioned upon an assertion that ultimately evaluates to the Boolean value of either true or false.

We declare variables of type bool as we declare variables of other types, by writing the name of the data type and then the variable name.

#include <iostream>

using namespace std;

int main(void){

    bool a = true;
    bool b = false;

    cout  <<  "bool a is "  <<  a  <<  endl;
    cout  <<  "bool b is "  <<  b  <<  endl;

    return 0;

}

Note that unlike in regular C, in C++ bool is a fundamental data type. As in C, false corresponds to 0 and true corresponds to a non-zero value, typically 1.

Boolean expressions are made up of logical values and operands. Every logical expression ultimately evaluates to either true or false. Relational operators enables us to compare two mathematical expressions and derive a logical value from it.

#include <iostream>

using namespace std;

int main(void){

    int x,y;
    bool returnValue;    

    cout << "Enter a number: ";
    
    cin >> x;

    cout << "Enter another number: ";

    cin >> y;

    returnValue =  x > y;

    cout << x << " > " << y << " : " << returnValue << endl;

    returnValue = x < y;

    cout << x << " < " << y << " : " << returnValue << endl;

    return 0;

}

The fundamental control structure that allows branches in the flow of control is the if statement. By using the if statement, we can ask a question in the form of a logical assertion and choose a course of action depending on how the assertion is evaluated. The if statement consists of the if keyword followed by a logical expression contained in parentheses, follow by the statement or statement block to be conditionally executed. Optionally, we can follow this statement or statement block with the keyword else, followed by a statement or statement block to be executed if the expression evaluated to false.

#include <iostream>

using namespace std;

int main(void){

    bool trueVal = true;

    if(trueVal){
        cout << "This statement will be displayed." << endl;
    } else {
        cout << "This statement will not be displayed." << endl;
    }

    if(trueVal==0){
        cout << "This statement will not be displayed." << endl;
    } else {
        cout << "But this one will, as Boolean true does not equal 0." << endl;
    }

    return 0;

}

Compound statements must be enclosed in curly braces. As a matter of style, it is considered best practice to include any statements whose execution is conditional in curly braces, even if there is only one statement.

Be aware that the else portion of an if-else statement is optional.

#include <iostream>

using namespace std;

int main(void){

    bool val;

    int a, b;

    a = 404;
    b = 8086;

    if(a!=b){
        cout << a << " does not equal " << b << endl;
    }

    if(a<b){
        cout << a << " is less than " << b << endl;
    }
    

    return 0;

}

It is possible to place and if statement within another if statement. By nesting our if statements, we can implement complex logic that enables our computer to deal in a nuanced manner with varying input. Nested if statements enable us to create multiway branches, were the flow of execution has more than two possible paths.

#include <iostream>

using namespace std;

int main(void){

    int temp = 40;

    if(temp > 20){
        if(temp < 33){
            cout << "Let's go for a hike " << endl;
        } else {
            cout << "Let's go swimming " << endl;
        }
    } else {
        if(temp > 0){
            cout << "Let's stay inside " << endl;
        } else {
            cout << "Let's go skiing " << endl;
        }
    }


    return 0;

}

Note that is important to consider human readability as well when designing branching structures.

 

 

 

 

 

Branching and Looping Statements in C++

We can control the flow of a program using branching  and looping statements. Branching statements give us code which is optionally executable, depending on the outcome of certain tests which we can define. Looping statements are used to repeat a section of code a number of times or until a condition has been reached.

First, we will look at branching statements in C++.

The single if statement is the simplest way to introduce branching into our programs.

#include <iostream>

using namespace std;

int main(void){

    bool condition = true;

    if(condition){
        cout  <<  "Condiditon was met. This code is executing. " << endl;
    }

    return 0;

}

The if statement tests an expression contained in the parentheses that follow that if keyword. If the expression evaluates to Boolean true, then the statement will be executed. As far as C / C++ is concerned, zero is false and anything non-zero is true.

#include <iostream>

using namespace std;

int main(void){
    int i = 5;
    int j = 0;

    //this program will only print output once, not twice
   
    if(i){
        cout  <<  "Condition was met."  <<  endl;
    }

    if(j){
        cout  <<  "Condition was met."  <<  endl;
    }

    return 0;

}

Note that the test condition can be an expression, as long as this expression evaluates to either 0 or a non-zero number. For example,  5 + 3, 4 – 7, and 3 * 2 all evaluate to true, as far as the C compiler is concerned.

We can also include relational operators in our test expressions. Relational operators allow us to test if a value is greater than, less than, or equal to another number. The equality operator is a bit unusual, in that it is two equals signs together, rather than just one.

#include <iostream>

using namespace std;

int main(void){

    char a = 'a';
    char b = 'A';

    if(a==b){
        cout  <<  "A and a are equal"  <<  endl;
    }

    //this is the option that prints
    if(a>b){
        cout  << "a is greater than A"  <<  endl;
    }

    if(a<b){
        cout  <<  "a is less than A"  <<  endl;
    }


    return 0;

}

An alternative form of the if statement is the if… else statement. The if… else statement executes one block of code if the statement evaluates to true, and another block of code if the statement is false. Much like the proverbial fork in the road, the if… else statement represents two mutually exclusive options.

#include <iostream>

using namespace std;

int main(void){

    if(5 < 3){
        cout  <<  "Either this happens."  <<  endl;
    } else {
        cout  <<  "Or this."  <<  endl;
    }
   
    return 0;

}

Of course, it is possible to nest if statements one within another.

#include <iostream>
#include <string>

using namespace std;

int main(void){
   
    string a = "Greetings, Professor Falken.";
    string b = "Someone set us up the bomb.";

    if(a == b){
        cout  <<  "string "  <<  a  <<  " and ";
        cout  <<  "string "  <<  b  <<  " are the same."  <<  endl;
    } else {
       
        cout  <<  "string "  <<  a  <<  " is ";
        if(a.length() < b.length()){
            cout  <<  "shorter ";
        } else {
            cout   <<   "longer ";
        }
        cout  <<  "than string "  <<  b;
    }
   
    return 0;

}

Computers are great at doing repetitive tasks. To get the computer to repeat a task, we need to use a looping statement in our program. The while statement is arguably the simplest looping statement. The while statement is like the if statement in that it evaluates a test condition in parentheses and then executes conditionally the following block of code. Unlike an if statement, the while statement will continue to execute the block of code again and again, until the test condition evaluates to false.

#include <iostream>
#include <string>

using namespace std;

int main(void){
   
    int condition = -10;

    //when condition reaches zero,
    //loop will stop
    //note the double parentheses
    while((condition = condition + 1)){
        cout  <<  condition  <<  " ";
    }

    cout  <<  endl  <<  endl;

    //when condition becomes greater than 10
    //loop will stop
    while(condition++ < 10){
        cout  <<  condition << " ";
    }
   
    cout  <<  endl  <<  endl;

    return 0;

}

For our final program, we will use a while loop to compute a Fibonacci sequence. Within the while loop we will also include a conditional statement which will cause the program to print a line break after every five numbers.

#include <iostream>
#include <string>

using namespace std;

int main(void){

    int previousNumber, currentNumber, temp;
    int breakCounter = 1;
    
    previousNumber = 1;
    currentNumber = 1;


    while(currentNumber < 10000){
        cout  <<  currentNumber  <<  "\t";

        temp = currentNumber;

        currentNumber = currentNumber + previousNumber;
                
        previousNumber = temp;

        if(breakCounter++ % 5 == 0)
        {
            cout  <<  endl;
        }
    }
    
    return 0;

}