Broad Network


C++ Conditional Statements

C++ Taking the Bull by the Horns – Part 6

Forward: In this part of the series, we see how a group of statements can be executed based on a condition.

By: Chrysanthus Date Published: 21 Aug 2012

Introduction

This is part 6 of my series, C++ Taking the Bull by the Horns. In this part of the series, we see how a group of statements can be executed based on a condition.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

The if Statement
In C++, there is a reserved word, which is “if”. The “if” must be in lowercase. This is used to check if a condition is true. If it is true, one or more statements are executed. Let us look at an example. Consider the following code:

#include <iostream>
using namespace std;

int main()
    {
        int hisVar = 20;

        if (hisVar == 20)
            {
                cout << "I am studying C++.";
            }

        return 0;
    }

There are two blocks here. The outer block is known as the block for the main function. We have seen this block many times. It is in this block of the main function that we have been writing a lot of our statements. There is another block inside the outer block (see its use below).

In the block of the main function, the first statement assigns the value 20 to the object identified by, hisVar. Then you have what is known as the if-construct. The if-construct begins with the reserved word, “if” and ends with the curly brace, }. What goes inside the parentheses is the condition. If this condition is true (correct), some statements are executed. The statements to be executed are in the curly braces, which form the inner block mentioned above. This inner block is independent of the outer block. In fact this inner block is part of the if-construct; that is how you should see it. Now, identify the block of the main function and that of the if-construct in the above code, if you have not already done so. If there is only one statement in the block of the if-construct, you do not need the curly braces for the if-block. If you have more than one statement, separate them with semicolons and put them within the curly braces, {} to form the if-block.

If the condition is correct, it will be replaced with, true, internally; you do not see it. If it is wrong, it will be replaced with, false, internally; you also do not see that.

In the above code, 20 was assigned to, hisVar. So, hisVar equals 20. In the condition the equal sign is two-assignment operators: one just next to the other. In math the equal sign is the assignment operator, while in C++, the equal sign is two-assignment operators. Remember, avoid making analogy between C++ and math. The if-construct above can be read like this: if hisVar equals 20 then display, 'I am studying C++'. Since we assigned the value 20 to the object identified by hisVar, the condition of the if-construct is true. So the statement in the curly braces is executed. Try the above code.

else
In the above code, the statement(s) in the curly braces is(are) executed if the condition is true. What about, if it were false? It would be false if we never assigned 20 to hisVar. If it were false, nothing will happen. That is, the statement(s) in the curly braces will not be executed. There is an else sub construct you can attach to the if-statement. The else part is similar in coding to the if-part. However, its block (curly braces) is executed when the if’s condition is false. The else part does not have any condition. Read and try the following code:

#include <iostream>
using namespace std;

int main()
    {
        int hisVar = 36;

        if (hisVar == 20)
            {
                cout << "I am studying C++.";
            }
        else
            {
                cout << "I am doing something else.";
            }

        return 0;
    }

In the above code, a value of 36 is assigned to hisVar. In the if-condition, we test if hisVar is equal to 20. So the condition returns false, and the statement(s) in the else block is (are) executed. Note how the else section has been typed. Also note that else is a reserved word. I will explain the other statements such as “return 0;” in the complete code above, later.

Reserved words also known as keywords, are words that have special meaning in C++ and you cannot use them arbitrary. Examples of reserved words we have seen are, if, else, int, float, _Bool, char, void and enum.

else if
You may have more than one test to make in a particular situation or for the same identifier. In this case you include the “else if” phrase as in the following code. Read and try it.

using namespace std;

int main()
    {
        int hisVar = 1000;

        if (hisVar == 10)
            {
                cout << "Value is small";
            }
        else if (hisVar == 100)
            {
                cout << "Value is medium";
            }
        else if (hisVar == 1000)
            {
                cout << "Value is large";
            }

        return 0;
    }

A value of 1000 is assigned to hisVar. The if-else-if coding will test if hisVar is 10; if it is (which it is not) the corresponding block will display 'Value is small'. The code will then test if hisVar is 100; if it is (which it is not), the corresponding block will display, 'Value is medium'. The code will then test if hisVar is 1000; if it is, the corresponding block will display, 'Value is large'. With the if-else-if coding only one of the blocks can be executed; that is, only one of the conditions can be true (the rest should be false).

In the if-else-if coding, the very first line must be the if-condition; the rest are else-if conditions. The “else if” phrase takes a condition, but the else reserved word never takes a condition.

Always remember this: the if-else-if coding is used only for situations where only one of the conditions is satisfied (is true).

Default Condition
What about the situation for an if-else-if coding where none of the conditions is true? For that situation you will need to report (inform the user) of something to that effect. This is an opportunity to give some default answer. You do this by simply adding the else (no condition) section at the end of the if-else-if coding. The following code illustrates this:

#include <iostream>
using namespace std;

int main()
    {
        int hisVar = 10000;

        if (hisVar == 10)
            {
                cout << "Value is small";
            }
        else if (hisVar == 100)
            {
                cout << "Value is medium";
            }
        else if (hisVar == 1000)
            {
                cout << "Value is large";
            }
        else
            {
                cout << "hisVar is very large";
            }

        return 0;
    }

Try the above code if you have not already done so. At the start of the code, 10,000 is assigned to the identifier. Note that when you are applying numbers with more than 3 digits, you do not use commas (you type 10000 and not 10,000). In the code, none of the conditions is satisfied, so the last block, which does not have any condition (which is the else part), is executed. Read through the code to appreciate this. Again, I will explain the other statements, like “return 0;” later in the series.

Complete Syntax for if-Construct
The complete syntax for the if-Construct is:

if (condition)
    {
        statements
    }
else if (condition)
    {
        statements
    }
else if (condition)
    {
        statements
    }

            -  -  -

else
    {
        statements
    }

Note: if the “if” or “else if” or “else” part has just one statement, then you do not need curly braces for the statement. You need curly braces if there is more than one statement.

The switch Statement
The previous code is replaced by the following. Read and try it.

#include <iostream>
using namespace std;

int main()
    {
        int hisVar = 10000;

        switch (hisVar)
            {
                case 10:
                cout << "Value is small";
                break;
                case 100:
                cout << "Value is medium";
                break;
                case 1000:
                cout << "Value is large";
                break;
                default:
                cout << "hisVar is very large";
            }

    return 0;
}

The syntax for the switch statement is:

switch (expression)
    {
       case label :
           statements;
           break;
       case label :
           statements;
           break;
       -  -  -
       default :
           statements;
    }

The word, expression in the parentheses above is an integer or any expression that returns an integer. An example is just an identifier, as in the above situation. label is the result of the expression. Each case section ends with “break;”. The last situation does not have a label (corresponds to else). Note the use of colons and semicolons. If you have more than one statement for a case, separate them with semicolons. Also note the use of the curly braces. You use the switch statement instead of the if-else-if statement, when you may want to compare the same identifier (or expression) with many different integers.

Quotation Marks
If your value is a number (int or float) in the condition, it should not be in quotes. If it is a string, you need to have it in double quotes. If it is a char you should have it in single quotes. There is actually more to strings than I have indicated, see later.

Let us stop here and continue in the next part of the series.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message