ICS 103: Computer Programming in C

Handout-06

Topic: Control Structures (Selection Structures)

 

Instructor: M. Waheed Aslam.

 

Objective:

if … else if … else,   switch  Selection Statements.

Control Structures(Selection, Repitition):

·        Refers to statements that control the flow of program (or function) execution.

·        In C, control structure enables us to combine individual instructions into a single logical unit with one entry point and one exit point.

·         Generally, there are three types of control structures: Sequence (What we are using until now); Selection; Repetition;

·        Compound Statement: Group of statements enclosed in { and }, used to indicate sequential flow. For example, function body consists of a single compound statement

{  statement 1;

    statement 2;

       .

       .

       .

    statement n;

}

 

·        Before going to Selection structures, we will discuss relational and logical operators of C language and know about the order of execution of relational and logical operators with others operators.

·        Also, we will discuss conditions and logical expressions because control structures rely on them.

 

Relational and Logical operators:

The most commonly used relational operators are

                >      for   greater than

                >=    for   greater than or equal to     relational

                <       for   less than                           operators                        

                <=     for   less than or equal to

                ==     for   equal to     -- Type is:    equality operator

                !=      for   not equal to   -- Type is: equality operator

 

        The most commonly used logical operators are

                &&    for   binary AND

                | |    for   binary OR

 

These operators are used in the expression of if statement. The expression having these operators is called Logical expression.

 

Examples:

To check if the value of the integer variable x is more than 5 and less than 10 or equal to 15, we write

                        if ( x > 5 && x < 10 | | x == 15 )

To check if the value of the float variable a is not equal to 1.5 or less than or equal to 2.5 but more than or equal to 1.5, we write

                        if ( a != 1.5 | | a <= 2.5 && a >= 1.5 )

 

Operator Precedence:

Operator                                                                                Precedence

Function calls                                               highest

Unary operators ! (not), +, -, & (address of)   2nd highest

*, /, %                                                                        

+,  _                                                                                     

<, <= , >=, >                                                                

== (equality operator), != (not equal)

&& (logical and operator)                                        

|| (logical OR operator)                                                                

= (assignment operator)                                 (Lowest)

Selection Structures:

One-Way Selection Using the if-statement:

Syntax:    if (expression)

                  Statement; 

If the expression is true, then the statement is executed; otherwise the statement is ignored.

 

For example, let marks be an integer variable. To check the value of marks to see if it is more than 75 and print PASS if it is more than 75 we would write

                if (marks > 75)

                 printf (“PASS\n”);

If marks is less than or equal to 75 then the print statement is ignored and nothing is printed.

 

If suppose that in addition to printing PASS we would like to add 5 bonus marks then we would write

                if (marks > 75)

            {   marks = marks + 5;

                 printf (“PASS\n”);

            }

As seen above if there is more than one statement (compound statement) to be done after checking the expression result, then the statements should be enclosed between parenthesis. If there is only one statement (simple statement) to be executed after if then the parenthesis becomes optional (you can remove it).  Note that there is no semi-colon at the end of the if or else statement.

 

Two-Way Selection Using the if…else statement:

Syntax:     if (expression)

                 statement  1;

            else

                  statement 2;

 

If the expression is true, then the statement 1 is executed; otherwise the statement 2 is executed if expression is false.

 

For example, to find the larger of two variables x and y and print the answer and assign the larger value to max variable and smaller value to min variable, we would write:

                if ( x > y )

            {     max = x;

                  min = y;

                  printf (“ x is BIG\n”);

            }

            else

            {      max = y;

                   min = x;

                   printf (“ y is BIG\n”);

            }

                 

Check for the parenthesis used for more than one statements after if and else.

Multiple Alternative Decision Using the if ladder:

Syntax:    if ( expression 1 )

                     statement  1;

            else if ( expression 2 )

                    statement 2;

                        .

                        .

                        .

              else if ( expression n )

                     statement n;

              else

                     statement e;

 

The expressions in a multiple-alternative decision are evaluated in sequence until a true condition is reached. If an expression is true, the statement following it is executed, and the rest of the multiple-alternative decision is skipped. If an expression is false, the statement following it is skipped, and the next expression is checked. If all the expressions are false, the statement e following the final else is executed.

 

For example, to check the value of the variable marks and print the message accordingly, we would write:

                if (marks >= 75)

                  printf (“Distinction\n”);

            else if (marks >= 60)

                  printf (“Pass\n”);

            else if (marks >= 50)

                  printf (“Average\n”);

            else

                  printf (“Fail\n”);

 


Nested if statements:

There can be if statements inside if and else statements which can be used to implement decisions with several alternatives.

For example,

                   if (x > 2.5)

            {     p = p + 1;

                  if (x < 3.5)

                      n = n + 1;

                  else

                      m = m + 1;

            }

            else

            {

                  if (x > 1.5)

                      s = s + 1;

                  else

                       t = t + 1;

            }

In the above example, if x is greater than 2.5 then 1 is added to p and it is checked if x is less than 3.5. If it is so, then 1 is added to n. If x is more than 3.5, 1 is added to m. If x is less than 2.5, the execution comes directly to the else part without doing anything to p, n, m and it is checked if x is more than 1.5. If it is so 1 is added to s else 1 is added to t.

 

Multiple selection using the switch statement:

 

Syntax:    

     switch  (expression)

      {

       case value 1:

                  statement 1;

                   break ;

       case value 2:

                  statement 2;

                   break ;

            :

            :

 

       case value n:

                  statement n;

                   break ;

       default:

                  statement e;

         }

 

Here it is checked whether the value of expression matches any of the case values.

 

For example: to check the value of the character variable color and print the message accordingly, we write

                   switch (color)

            { case ‘R’:

                 printf (“red\n”) ;   break ;

              case ‘B’:

                  printf (“blue\n”) ;   break ;

              case ‘Y’:

                  printf (“yellow\n”) ;   break ;

              default:

                  printf (“black\n”) ;   break ;

            }

The single quotes ‘R’,’B’,’Y’ are used because of the color being character variable. If color is ‘R’ then red is printed and the other cases are not checked, however if color is not red then other cases are checked until a match is found. If no match is found then the default value of black is printed. 

Solved Examples:

Use of Control Structures (Selection Structures)

Example#1:

/*******************************************************************/

Write a program that calculates and displays the reciprocal of an integer, both as a common fraction and a decimal fraction.

 

A typical output line would be: The reciprocal of 2 is 1/2 or 0.500

 

The program should display a Reciprocal undefined message for an input of zero.

/******************************************************/

#include<stdio.h>

void main ()

{

int number;

float reciprocal;

printf("please Enter an integer number:  ");

scanf("%d",&number);

if (number>0  ||  number<0)

         { reciprocal = 1.0/number;

         printf("\nThe reciprocal of %d is 1/%d or %0.3f",number,number,reciprocal);

    }

    else

         printf("\nReciprocal undefined");

    } // end of main

Sample Output:

 

Example#2:

/********************************************************

Write an interactive program that contains a compound if statement and that may be used to compute the area of a square (area=side2) or a triangle (area=base*height/2) after prompting the user to type the first character of the figure name (S or T).

*******************************************************/

/*******************************************************/

Using If statement.

/*******************************************************/

#include<stdio.h>

void main ()

{ int side, height, base, area;

  char D,S,T;

  printf("If you want area of a square press S or T for area of triangle :");

  scanf("%c", &D);

  if (D=='S')

  {      printf("please input the side : ");

        scanf("%d", &side);

        area=side*side;

        printf("The area : %d\n", area);

   }

  else if (D=='T')

 {       printf("Enter base and height of the triangle :");

         scanf("%d %d", &base, &height);

         area=(0.5)*base*height;

         printf("The area of triangle is : %d", area);

   }

  } // end of main

Sample Output:

/***************************************************************/

Using Switch statement

/****************************************************************/

#include<stdio.h>

void main( )

{char choice;

double side, height, base, area;

printf("[To find the shape's area choose either 'S' for square, or 'T' for triangle]:");

printf("\nEnter your choice to find the area: ");

scanf("%c", &choice);

switch(choice)

    {      case 'S': printf("\nEnter its side: ");

                        scanf("%lf", &side);

                        area = (side * side);

                        printf("The area of square is %.2f unit square\n", area);

            break;

        case 'T' : printf("\nEnter the height and base: ");

                       scanf("%lf %lf", &height,  &base);

                       area = (0.5) * height * base;

                       printf(" The area of triangle is %.2f unit square\n", area);

            break;

   default: printf("Sorry ,your choice is not included \nPlz try again ");

        }

     } // end of main

Sample Output:

 

Homework

Trace output of following program manually (Without using Computer) :

#include<stdio.h>

main( )

{int j, x=0;

switch(j-1)

{case 0 :

case -1 :

x += 1;

break;

 

case 1:

case 2:

case 3:

x += 2;

break;

 

default:

x += 3;

}

printf("x = %d\n", x);

}

Output: