Categories
Computer Science / Information Technology Language: C

Decision Control Statements

Many times, we want a set of instructions to be executed in one situation, and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt with in C programs using decision control instruction. A decision control instruction can be implemented in C using:

  • The if statement
  • The if-else statement
  • The conditional operators

The if statement

C uses the keyword ‘if’ to implement the decision control instruction. The general form of if statement looks like this:

if ( this condition is true )
    execute this statement;

The keyword ‘if’ tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead, the program skips past it. A condition can be expressed using C’s ‘relational’ operators which are listed in the following table:

ExpressionExplanation
x == yx is equal to y
x != yx is not equal to y
x < yx is less than y
x > yx is greater than y
x <= yx is less than or equal to y
x >= yx is greater than or equal to y
Relational operator expressions example

The following example program illustrates the if statement. It reads the age of the user and determines if the user can vote.

#include <stdio.h>
int main() 
{
    int age;
    scanf("%d", &age);
    if (age > 18)
        printf("Eligible");
    return 0;
}

Expression as condition

An expression can be any valid expression including a relational expression which can be used as a condition inside of if. We can even use arithmetic expressions in the if statement. For example, all the following if statements are valid

if ( 3 + 2 % 5 )
    printf ( "This works" ) ;
if ( a = 10 )
    printf ( "Even this works" ) ;
if ( -5 )
    printf ( "Surprisingly even this works" ) ;

Points to note:

  • Note that in C a non-zero value (integer or float) is considered to be true, whereas a 0 is considered to be false. Hence all three printf() statements get executed in the above example.
  • In the second if, 10 gets assigned to a so the if is now reduced to if ( a ) or if ( 10). Since 10 is non-zero, it is true hence again printf( ) gets executed.

Multiple Statements within if

It may so happen that in a program we want more than one statement to be executed if the expression following if is satisfied. If such multiple statements are to be executed then they must be placed within a pair of braces as illustrated in the following example.

#include <stdio.h>
int main()
{
    int age;
    scanf("%d", &age);
    if (age > 18)
    {
        printf("Eligible");
        printf("Please get the voter id ready");
    }
    return 0;
}

If the pair of brackets enclosing the printf() statements under if is removed, the compiler considers only the first statement as the if block. Hence the default scope of the if statement is the immediately next statement after it.

The if-else statement

if statement executes a set of statements when the condition placed in it evaluates to true. It does nothing when the expression evaluates to false. An else block coupled with an if block helps in executing a totally different set of instructions when the condition fails. Consider the same voter example which we saw earlier. The program should check if the age is greater than 18. And if it is not, the program should print “Not eligible”.

#include <stdio.h>
int main() 
{
    int age;
    scanf("%d", &age);
    if (age > 18)
    {
        printf("Eligible");
        printf("Please get the voter id ready");
    }
    else 
    {
        printf("Not eligible");
        printf("Wait for appropriate age");
    }
    return 0;
}

Points to note:

  • The group of statements after the if up to and not including the else is called an ‘if block’. Similarly, the statements after the else form the ‘else block’.
  • Notice that the else is written exactly below the if. There should not be any statement between the if block and else block. This will raise a compilation error.
  • Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces.
  • As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope a pair of braces as shown in the above example must be used.

Nested if-else

It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called nesting of ifs. This is shown in the following program:

#include <stdio.h>
int main() 
{
    int n;
    scanf("%d", &n);
    if (n % 3 == 0)
        printf("Divisible by 3");
    else 
    {
        if (n % 5 == 0)
            printf("Divisible by 5");
        else
            printf("Neither divisible by 3 nor 5");
    }
    return 0;
}

Use of logical operators

Logical operators (‘AND’, ‘OR’, ‘NOT’) are extensively used in conditional statements. These operators can be used to reduce the nesting and complexity of the conditional statements. Consider the following example where the percentage of a student is read and the class is printed based on the following criteria:

  • Percentage above or equal to 60 – First division
  • Percentage between 50 and 59 – Second division
  • Percentage between 40 and 49 – Third division
  • Percentage less than 40 – Fail
#include <stdio.h>
int main() 
{
    float per;
    scanf("%f", &per);
    if ( per >= 60 )
            printf ( "First division ") ;
    else 
    {
            if ( per >= 50 )
                printf ( "Second division" ) ;
            else 
            {
                if ( per >= 40 )
                    printf ( "Third division" ) ;
                else
                    printf ( "Fail" ) ;
            }
    }
    return 0;
}

Points to note:

  • As the number of conditions goes on increasing the level of indentation also goes on increasing. As a result, the whole program creeps to the right.
  • Care needs to be exercised to match the corresponding ifs and elses.
  • Care needs to be exercised to match the corresponding pair of braces.
  • The readability of the program takes a serious hit.

The same program can be rewritten using logical operators as follows and all the above disadvantages can be eliminated:

#include <stdio.h>
int main()
{
    float per;
    scanf("%f", &per);
    if ( per >= 60 )
        printf ( "First division ") ;
    if ( ( per >= 50 ) && ( per < 60 ) )
        printf ( "Second division" ) ;
    if ( ( per >= 40 ) && ( per < 50 ) )
        printf ( "Third division" ) ;
    if ( per < 40 )
        printf ( "Fail" ) ;
    return 0;
}

Points to note:

  • The mismatching of the ifs with their corresponding elses gets avoided.
  • In spite of using several conditions, the program doesn’t creep to the right

The else-if clause

The else-if clause (also called as if-else-if ladder) gives a powerful way of handling multiple cases and possibilities. The syntax is as follows:

if (condition)
    statement 1;
else if (condition)
    statement 2;
.
.
else
    Statement;

Here, the last else statement is optional. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.


Consider the same example of the printing class of the student based on the percentage. It can be written in a different way using else-if as follows:

#include <stdio.h>
int main() 
{
    float per;
    scanf("%f", &per);
    if ( per >= 60 )
        printf ( "First division ") ;
    else if ( ( per >= 50 ) && ( per < 60 ) )
        printf ( "Second division" ) ;
    else if ( ( per >= 40 ) && ( per < 50 ) )
        printf ( "Third division" ) ;
    else
        printf ( "Fail" ) ;
    return 0;
}

Points to be noted

  • This program reduces the indentation of the statements. In this case, every else is associated with its previous if.
  • The last else goes to work only if all the conditions fail.
  • No other statements should be placed between the ladder. If there are multiple statements in an else-if case, they have to be enclosed in brackets.

Advantages of the else-if clause:

  • In case if-else had to replicate the output logic of the else-if ladder, it would be more complex. The following example illustrates the contrast between the two:
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else
printf("i is not
present");

if (i == 10)
printf("i is 10");
else {
if (i == 15)
printf("i is 15");
else
printf("i is not present");
}

Common mistakes

Using assignment operator instead of ‘==’ comparison operator as shown:

#include <stdio.h>
int main() 
{
    float per = 8.9;
    if ( per = 7.9 );
    printf ( "Same");
    return 0;
}

The program will print “Same” irrespective of the value of ‘per’.

  • Putting semicolon at the end of if() such as follows:
#include <stdio.h>
int main() 
{
      float per = 8.9;
      if ( per == 7.9 );
      printf ( "Same");
      return 0;
}

The above program prints “Same”.

  • Comparing floating-point variables with double. Consider the following example.
#include <stdio.h>
int main() 
{
    float per = 8.9;
    if ( per == 8.9 )
    printf ( "Same");
    else
    printf("Different");
    return 0;
}

The output of the above program will surprisingly be “Different” as ‘8.9’ is double and ‘per’ is float and they are not the same.

The conditional operators / Ternary operators

The conditional operators ‘?’ and ‘:’ are sometimes called ternary operators since they take three arguments. They form a foreshortened if-then-else. The general form is:

expression 1 ? expression 2 : expression 3 

This decodes to:

if expression 1 is true, then the value returned will be expression 2, otherwise, the value returned will be expression 3.

Example: y = ( x > 5 ? 3 : 4 ); The above statement assigns y to 3 if the value of x is greater than 5 and 4 otherwise.

Points to note:

  • Conditional operators could be used for statements other than arithmetic statements. This is illustrated as follows:
    • ( i == 8 ? printf (“QM”) : printf (“C Programming”)) ;
    • printf ( “%c” , ( a <= ‘z’ ? a : ‘!’ ));
  • The conditional operators can be nested as shown below.
    • big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ));
  • Consider the following conditional expression:
    • a > b ? g = a : g = b ;
    • This will make the compiler throw an error ‘Lvalue Required’. The error can be overcome by enclosing the statement in the : part within a pair of parenthesis. This is shown below:
    • a > b ? g = a : ( g = b ) ;
  • In absence of parentheses, the compiler believes that b is being assigned to the result of the expression to the left of second =. Hence it reports an error.
  • The limitation of the conditional operators is that after the ? or after the : only one C statement can occur. In practice rarely is this the requirement.

Excercise

  1. If cost price and selling price of items is given, write a program to determine whether the seller has made profit or incurred loss and print how much profit he made or loss he incurred.
  2. Write a program to find out whether a given number is odd or even.
  3. Given an year, write a program to determine whether it is a leap year or not.
  4. According to the Gregorian calendar, it was Monday on the date 01/01/1900. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.
  5. Given a five-digit number, write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.
  6. Given 3 numbers, print the minimum, maximum and average of them.
  7. Given the three angles of triangle, check if the triangle is valid or not.
  8. Find the absolute value of a number entered through the keyboard.
  9. Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter.
  10. Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.
  11. Given the coordinates (x, y) of a center of a circle and it’s radius, write a program which will determine whether a point lies inside the circle, on the circle or outside the circle. (Hint: Use sqrt( ) and pow( ) functions)
  12. Given a point (x, y), write a program to find out if it lies on the x-axis, y-axis or at the origin, viz. (0, 0).
  13. Given the three sides of a triangle, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.
  14. If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page