Module 3. Control statements

Lesson 10

Decision Control STATEMENTS

10.1  Decision Control Statements

A programme consists of a number of statements, which are usually executed in a particular sequence. Programming can be made powerful, if one can control the order in which statements are performed. Generally, this is achieved with decision control statement (also known as selection statements).  These statements are used to create special programme features such as decision making or branching structures (i.e., logical tests). In a nutshell, a decision control statement makes decision about the next course of action depending upon different options and or conditions. ‘C’ supports a variety of decision control statements as described below.

10.2  if…else Statement

The if…else statement is used to decide whether to perform an action at a special point or to decide between two courses of action. The general syntax is as follows:

if (conditional expression)statement;

This can be extended with else option to choose a course of action out of two available options as follows:

if (conditional expression)statement_1;

else statement_2;

Thus, if the underlying expression comes out to be TRUE, the statement_1 is executed, otherwise statement_2 is performed.

Illustration

The following code snippet tests whether a student passed an examination with the passing marks as 60.

if (marks >= 60)

        printf(“Pass\n”);

else

        printf(“Fail\n”);

In this example, within if statement, the underlying conditional expression is evaluated and for its truth value, i.e., TRUE or FALSE. If it is TRUE, the message ‘Pass’ is displayed on output device, otherwise else statement is executed and it displays ‘Fail’ as the output.

In case there are multiple statements to be performed depending on the truth value of the conditional expression, they are embedded in curly brackets, {}.

Illustration

if (marks >= 60)

{       printf(“Congratulations\n”);

        printf(“You have passed the examination\n”); 

}

else

{       printf(“Work hard\n”);

        printf(“You failed the examination\n”); 

                 }

10.3  Nested if…else Statement

Sometimes, you have to make a multi-way decision based on several conditions. This is achieved by cascading several comparisons; and depending upon the result of these multiple comparisons, the following statement or block of statements is executed. The moment, one of these comparisons gives a TRUE value, no further comparisons are performed.

Illustration

Assume that grades are awarded to the students depending on the examination results. Grade ‘A’ is given to the students having marks greater than or equal to 80; Grade ‘B’ to the students securing marks (equal to or more than 60 but less than 80); Grade ‘C’ for the marks (equal to or greater than 45 but below 60) and students attaining less than 45 marks are considered to be ‘failed’.

if (marks >= 80)

        printf(“Passed: Grade A\n”);

else if (marks >= 60 && marks < 80)

        printf(“Passed: Grade B\n”);

else if (marks >= 45 && marks<60)

        printf(“Passed: Grade C\n”);

else

        printf(“Failed\n”);

In this example, all comparisons test a single variable, i.e., marks. First step is to check whether ‘marks are greater than or equal to 80’, if this condition comes out to be TRUE, it prints the message ‘Passed: Grade A’ and exits the if statement (to take up next statement in programme); otherwise it moves onto the next else if statement, i.e., the condition ‘the marks lie between 60 and 80’, if it is found TRUE, the output will be ‘Passed: Grade B’ and exits the if statement; otherwise, it further goes to the next else if statement to check whether ‘marks lie between the range, 45 to 60’, if this condition is found TRUE, the message ‘Passed: Grade C’ is printed and exits the if statement; otherwise the message ‘Failed’ is printed finally and exits the if statement.

10.4 switch and break Statements

10.4.1 switch statement

The switch statement is another form of the multi-way decision-making statement. It is well structured, but can only be used in certain cases where only one variable is to be tested and all branches must depend on the value of that variable. The variable must be an integer type or character type. In switch statement, different cases are presented and are checked one by one to see if one case matches the value of the underlying constant expression. If a case matches, its block of statements is executed. If none of the cases match, the default code is executed. The general syntax of switch statement is:

switch (expression)

            {

              case constant_1:

                 statement;

                 break;

              case constant_2:

                 statement;

                 break;

                 .  

                 .

                 .   

             default:

                 statement;

            }

10.4.2 break statement

break statement is used to force an early exit from a loop (discussed in next Lesson-11) or a switch; hence, control passes to the first statement beyond the loop or a switch. With loops, break can be used to exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an ‘if’ statement, which provides the test to control the exit condition.

Illustration   

Consider addition and multiplication of two numbers using switch statement.

int a, b;

int ch;

scanf(“%d %d %d”, &a, &b, &ch);

switch(ch)

 {

  case 1:

     result = a+b;

     break;

  case 2:

     result =a*b;

     break;

  default:

     printf(“Wrong Choice!”);

 };                      

Here, ch is taken as int type constant expression. The value of this expression decides as to which case is to be executed, i.e., if the value of the expression, ch comes out to be 1, the case 1 will be executed leading to addition of the two numbers and break statement prevents any further statements contained within the switch statement, from being executed by leaving the switch; and if ch comes out to be 2, the  case 2 statements are executed thereby computing multiplication of the two numbers, and break statement will leave switch statement. If the expression, ch assumes any value other than 1 and 2, the default code is executed, displaying the message “Wrong Choice!” on the output device.

10.5  goto Statement

‘C’ has a goto statement, which permits unstructured jumps to be made. The goto statement is used to alter the programme execution sequence by transferring the control to some part of the programme. The general syntax is:

                               goto statement lable;

where lable is valid ‘C’ identifier used to label the destination. There are two ways of using the goto statement:

10.5.1  Unconditional goto statement

The unconditional goto statement is used to transfer the control from one programme part to other part without checking any condition.

Illustration 1

{

Begin : printf(“Welcome!”);

goto Begin;

}

Here, Begin is a label. First of all, printf function is executed and then the control moves onto the goto statement, which further passes the control to the label, Begin without any condition and this process repeats. Hence, an infinite loop is set up, which keeps on printing the message ‘Welcome!’ repeatedly! It can be stopped externally.

Illustration 2

In a difficult programming situation, it seems so easy to use a goto statement to take the control where you want. You can understand the use of goto keyword with the help of the following example:

main( )
{
 int goals ;
 printf("Enter the number of goals scored against India ") ;
 scanf("%d", &goals) ;
 if (goals<=5)
    goto sos;
 else
 {
    printf("About time soccer players learnt C\n");
    printf("and said goodbye! Goodbye! to soccer");
    exit(); // stops programme execution
 }
 sos:
 printf("To err is human!");
}

Test Output

Enter the number of goals scored against India 10

About time soccer players learnt C

and said goodbye! Goodbye! to soccer

Explanation

If the underlying condition is fulfilled, the goto statement transfers control to the label ‘sos’, causing printf function statement labelled ‘sos’ to be executed. Note the following points:

·         The label can be on a separate line or on the same line as the statement following it, as in,
sos: printf ("To err is human!");

·         Any number of goto statements can take the control to the same label.

·         The exit() function is a standard library function, which terminates the execution of the programme. It is necessary to use this function since we don’t want the statement: printf ("To err is human!"); to get executed after execution of the else block.

·         The only programming situation in favour of using goto is when we want to take the control out of the loop that is contained in several other loops.

10.5.2  Conditional  goto statement

The conditional goto statement passes the control of execution from one part of the programme to other, depending upon some condition case.

Illustration: Consider the following code segment.

int a = 9, b = 3;

if(a > b)

goto out_1;

else

goto out_2;

out_1: printf(“ a is largest”);

return;

out_2: printf(“ b is largest”);

Here, a and b are two variables of integer type. The ‘if’ statement compares a and b; obviously, in this case, the resultant value comes out to be TRUE; accordingly, the goto statement passes the control to the label, out_1; otherwise, the control will be transferred to the label, out_2. The students may like to interchange the values of a and b in the above code segment (i.e., a = 3, b = 9) and try to re-compile and run the same to see the effect of ‘else’ part of the aforementioned ‘if’ statement; in this case, the control will be sent to the out_2 label.

Example 1: Programme to calculate tax for a given amount of salary according to pre-defined criteria as specified in the algorithm given under Exercise-1 of Lesson-1.

/*  A ‘C’ program for the algorithm given in Exercise 1, Lesson 1  */

#include <stdio.h>

void main()

{

 long int salary;

 long float tax;

 printf("\nEnter salary : ");

 scanf("%ld", &salary);

 if (salary < 50000)

    tax = 0;

 else if (salary > 50000 && salary < 100000)

          tax=50000*0.05;

 else

          tax=100000*0.30;

 printf("\nTax : %lf", tax);

}

Output:

Enter salary : 100267

Tax : 30000.000000

Example 2: Let us see what output the following typical code produces upon its execution?

#include<stdio.h>

void main()

{

    int m=5,n=10,q=20;

    if(q/n*m)

         printf(" Sree Rama");

    else

      printf(" Sree Krishna");

    printf(" Mahadev Shiv");

     }

Output:

Sree Rama Mahadev Shiv

Explanation

Consider the following expression:

     q / n * m

In this expression there are two operators, viz., / (division operator) and * (multiplication operator). You know both the operators have same precedence and associativity from left to right. Thus, in this case, associativity decides, which operator executes first. Accordingly, the division operator (/) is executed first followed by multiplication (*) operator, as follows:

q / n * m

= 20 / 10 * 5

= 2 * 5

=10

Recall that in ‘C’, zero represents FLASE and any non-zero number represents TRUE. Since the resultant value in above case comes out to be 10, which is a non-zero number; therefore, ‘if’ clause will execute and print: Sree Rama.

Now, note that in the ‘else’ clause above, there are no opening and closing curly brackets. Therefore, compiler considers only one statement as a part of the ‘else’ clause. Thus, last statement, i.e.,

     printf(" Mahadev Shiv");

is not part of if…else statement. Hence, at the end compiler also prints: Mahadev Shiv. Therefore, the output of above code is:

Sree Rama Mahadev Shiv

Example 3: What output the following code would produce when executed?

#include<stdio.h>

void main()

{

    if(!printf("Sree Rama"))

        if(printf(" Sree Krishna"));

}

Output:

Sree Rama

Explanation:

Note that the printf statement is a kind of function (discussed later) and every function generally returns some value as an outcome. The return type of printf function is int. That is., this function returns an integral value, which is equal to the number of characters a printf function will print on the screen. Thus, in the present example, first of all, printf function will print: Sree Rama. Since, it is printing 9 characters; therefore, it will return value as 9. Hence, the ‘if’ condition, !printf("Sree Rama")comes out to be equivalent to !(9), which is equal to 0. As stated earlier, in ‘C’, zero represents FALSE. Thus, if(0) is FALSE in present case; accordingly, the next statement embedded inside the body of the first ‘if’ statement will not execute.