Broad Network


Selection Statements in C

Part 8 of Complete C Course

Foreword: Selection statements in C are the different if-statements.

By: Chrysanthus Date Published: 31 May 2024

Introduction

A program can be seen as consisting of simple statements. Some of the simple statements are grouped into blocks. A selection statement has one or more controlling expressions (conditions) that determine which block of the whole selection statement is executed.

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 (controlling expression) is true. If it is true, one or more statements are executed. Consider the following code:

    #include <stdio.h>

    int main(int argc, char *argv[])
    {
        int hisVar = 20;

        if (hisVar == 20)
            {
                printf("I am studying C.\n");
            }
        
        return 0;
    }

There are two blocks here. The outer block is known as the block for the main() function. This block has been introduced before (in the previous tutorials). It is in this block of the main() function, that a lot of the statements so far, have been written. There is another block inside the outer block (see its use next).

In the block of the main() function, the first statement assigns the value 20 to the object identified by, hisVar. Then there is the if-construct (if-statement). The if-statement begins with the reserved word, “if” and ends with the brace, }. What goes inside the parentheses is the condition (controlling expression). If this condition is true (correct), some statements are executed. The statements to be executed are in the braces (curly brackets), 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. If there is only one statement in the block of the if-construct, the braces are not needed for the if-block. If there is more than one statement, separate them with semicolons and put them within the braces, {} to form the if-block.

If the condition is correct, it will be replaced with, true, internally; this is not seen by the programmer. If it is wrong, it will be replaced with, false, internally; the programmer does 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 in a condition (controlling expression) 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 the value, 20 was assigned to the object identified by hisVar, the condition of the if-construct is true. So the statement in the braces is executed. Test the above code.

Note that only the first argument of the printf() function has been used. The ‘\n’ character sequence at the end of the string (text), is to make the cursor go to the next line at the end of the current line, at the terminal (output).

Note, so far in these tutorials, no statement has been written outside the main() function.

else

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

    #include <stdio.h>

    int main(int argc, char *argv[])
    {
        int hisVar = 36;

        if (hisVar == 20)
            {
                printf("I am studying C.\n");
            }
        else
            {
                printf("I am doing something else.\n");
            }
        
        return 0;
    }

In the above code, a value of 36 is assigned to hisVar. The if-condition, tests 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. The main() function should always end with “return zero;”.

Reserved words, also known as keywords, are words that have special meanings in C and cannot be used arbitrarily. Examples of some of the reserved words in C, that have been presented so far, are: if, else, int, float, _Bool, char, and void.

else if

There may be more than one test to make in a particular situation, or for the same identifier. In this case, the “else if” phrase is included as in the following code. Read and test it.

        int hisVar = 1000;

        if (hisVar == 10)
         {
                printf("Value is small\n");
         }
        else if (hisVar == 100)
         {
                printf("Value is medium\n");
         }
        else if (hisVar == 1000)
         {
                printf("Value is large\n");
         }

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 would display “Value is small”. The code will then test if hisVar is 100; if it is (which it is not), the corresponding block would 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, a report (inform the user) will have to be sent to the user, to that effect. This is an opportunity to give some default answer. This is done by simply adding the else (no condition) section at the end of the if-else-if coding. The following code illustrates this:

        int hisVar = 10000;

        if (hisVar == 10)
            {
                printf("Value is small\n");
            }
        else if (hisVar == 100)
            {
                printf("Value is medium\n");
            }
        else if (hisVar == 1000)
            {
                printf("Value is large\n");
            }
        else
            {
                printf("hisVar is very large\n");
            }

The reader should read and test the above code, if he/she has not already done so. At the start of the code, 10,000 is assigned to the identifier. Note: when applying numbers with more than 3 digits, do not use commas (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.

Complete Syntax for if-Statement
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 there is no need for the curly brackets, for that statement. Curly brackets are needed, if there is more than one statement.

The switch Statement
The previous code is replaced in the following program. Read and test it.

    #include <stdio.h>

    int main(int argc, char *argv[])
    {
        int hisVar = 10000;

        switch (hisVar)
            {
                case 10:
                    printf("Value is small\n");
                    break;
                case 100:
                    printf("Value is medium\n");
                    break;
                case 1000:
                    printf("Value is large\n");
                    break;
                default:
                    printf("hisVar is very large\n");
            }
        
        return 0;
    }

The syntax for the switch statement is:

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

The controlling expression in the parentheses above is an integer or any expression that results in an integer. An example is just an identifier, as in the above situation. “case” is a reserved word. It is an example of what is called a label. A possible result of the controlling expression, is typed after the case label. Each case section ends with “break;” (without the quotes). The last part does not have a label (corresponds to else). Note the use of colons and semicolons (a colon after a label expression). If there are more than one statement for a case, separate the statements with semicolons. Also note the use of the braces (curly brackets). Use the switch statement instead of the if-else-if statement, when the controlling expression is effectively an integer.

Quotation Marks
In programming, if the value is a number (int or float) in the condition, it should not be in quotes. If it is a string, it has to be in double quotes (at both ends). If it is a char, it has to be in single quotes (at both ends). There is actually more to strings than have been indicated here - see later.

Conclusion
A program can be seen as consisting of simple statements. Some of the simple statements are grouped into blocks. A selection statement has one or more controlling expressions (conditions) that determine which block of the whole selection statement is executed.

The if-constructs are:

- if
- if-else
- if-else-if
- if--else-if--else

The complete switch statement is a complete if--else-if--else statement, but focused on one integer, for its conditions.



Related Links

More Related Links

Cousins

BACK NEXT

Comments