EKT150 INTRODUCTION TO
COMPUTER PROGRAMMING
        Control Structure:
         Selection Part I
  Dr Nik Adilah, Dr Nur Hafizah & Mdm Rusnida Romli
    School of Computer & Communication Engineering
                   Outline
• Intro to control structure
• Types of selection
   – One-way selection
   – Two-way selection
   – Multi-selection
• Compound statement
         Learning Objectives
• Apply concepts for developing algorithms, using
  variables and structuring a C program
• Explain what is meant by a control structures
• Explain the three basic types of control structures
               Control Structure
• All programs can be written in terms of three
  control structures (like building blocks)
  1. Sequence Structure
  2. Selection Structure
  3. Repetition Structure
                1. Sequence Structure
• Sequence Structure
   – ‘Built-in’ to C
       • Unless otherwise directed, one statement after the next is executed
       • Is a series of steps executed sequentially by default
                Pseudo Code                             Flow Chart
            •                                                Begin
                 Begin
            •    Input A and B                        Read input A,B
            •    Calculate A + B
            •    Print result of                     Calculate A + B = SUM
                 SUM
            •    End                                     Print SUM
                                                            End
           2. Selection Structure
• Used to choose among alternative courses of action
• Used to control the flow of a program
• Also called as decision or branches
• Branches are conditions or choices used to enable
  selection of program flow
• C has three types:
   – If selection statement (one-way selection)
   – If…else selection statement (two-way selection)
   – Switch selection statement (multiple selection)
         One Way Selection : if
• if structures is a single-entry/single-exit structure
• The primary tool of selection structure
• Used when we want a single or a group of
  statements to be executed if the condition is true.
• If the condition is false, the statement is skipped
  and program continues by executing the first
  statement after the if selection structure
• Condition is express as a statement and two
  possible outcomes are indicate by true and false
               if syntax – Part 1
if (test expression)
{
    statement/s to be executed if test expression is true;
}
• Exercise:
    – Draw flowchart for the syntax above.
Flow Chart : if Selection
         Test       True
      expression
                   Statement (s)
    False
            if syntax – Part 2
if (this logical expression is true)       NO SEMI-COLON!
{
     statement 1;
}
next_statement;
• The expression in parentheses can be any expression that
  results in a value of true or false
• If the expression is true, Statement 1 is executed, after
  which the program continues with next_statement
• If the expression is false, Statement 1 is skipped and
  execution continues immediately with next_statement
if statement : Basic Understanding
Example :
  Is it raining?
   If the answer yes, take umbrella
     Then walk to work
  Exercise:
  • Draw flowchart for the above statement
   If statement : Flow Chart
                 False                    False
  Expression              Is it raining
True                     True
  Statement              Take umbrella
Next Statement           Walk to work
          If statement : Example 1
#include <stdio.h>
int main() {
   int num;
   printf("Enter a number to check.\n");
   scanf("%d",&num);
   if (num<10)/* checking whether number is less than 0 or not. */
      {
   /*If test condition is true, statement below will be executed,
otherwise it will not be executed */
        printf("Number = %d\n",num);
      }
    printf("if statement in C programming is easy.");
    return 0;
}
                 Exercise:
                 • Draw flowchart for the above code
                 • Predict and display the output
        If statement : Example 1
            Begin
                                    Enter a number to check:
                                    11
                                    If statement in C programming is easy
      Read input Num
                            False
         Num<10
                                    Enter a number to check:
     True                           5
                                    Number= 5
       Display Num                  If statement in C programming is easy
                                    Enter a number to check:
Display “ If statement in           10
C programming is easy”              If statement in C programming is easy
             End
       If statement : Example 2
int main ()
{
   int num;
   printf (“Enter a number between -10 and 10:\n”);
   scanf (“%d”, &num);
   if (num > 0)
      printf (“%d is a positive number\n”, num);
   return 0;
}
Exercise:
• Draw flowchart for the above code
• Predict and display the output
       if statement : Example 2
           Begin
                                     Enter a number between -10 and 10:
                                     7
    Read input num
                                     7 is a positive number
                             False
        num> 0
    True                             Enter a number to check:
                                     -1
Display “num is a positive
         number”
            End
         If statement : Example 3
#include <stdio.h>
int main (void)
{
   int number = 0;
   printf (“\nEnter an integer between 1 and 10\n”);
   scanf (“%d”, &number);
     if (number > 3)
        printf (“%d is greater than 3\n”, number);
      if (number < 6)
        printf (“%d is less than 6\n”, number);
   return 0;
}
   Exercise:
   • Draw flowchart for the above code
   • Predict and display the output
             If statement : Example 3
                 Begin
                                             Enter an integer between 0 and 10:
        Read input number
                                             5
                                             5 is greater than 3
                                             5 is less than 6
                                     False
            number>3
          True                               Enter an integer between 0 and 10:
Display “number is greater than 3”           2
                                             2 is less than 6
                                     False   Enter an integer between 0 and 10:
            number < 6
                                             10
          True                               10 is greater than 3
 Display “number is less than 6”
                  End
           If statement : Example 4
• Write flow chart and a C program to determine if the student pass
  based on an average of 2 test marks. The pass marks is 40 and
  above.
            If statement : Example 4
• Write a flow chart and C program to determine if the student pass
  based on an average of 2 test marks. The pass marks is 40 and
  above.
               Begin
     Read input test1 and test 2
     Calculate average marks,
       ave= (test1+test2)/2;
              Ave >=40
           True
                                   False
         Display “Passed”
                  End
            If statement : Example 4
• Write a flow chart and C program to determine if the student pass
  based on an average of 2 test marks. The pass marks is 40 and
  above.
                                           #include<stdio.h>
               Begin
                                           int main()
     Read input test1 and test 2           {
                                               float test1,test2,ave;
                                               printf(“Please enter 2 test marks”);
     Calculate average marks,                  scanf(“%f %f”,&test1,&test2);
       ave= (test1+test2)/2;
                                               ave=(test1+test2)/2;
              Ave >=40                         if(ave>=40)
           True                                  printf(“Passed”);
                                   False
         Display “Passed”                      return 0;
                                           }
                  End
  Two Way Selection : if … else
• Specifies and action to be performed
  both when the condition is true and
  when it is false
• If the boolean expression (or statements)
  evaluates to true, then the if block of
  code will be executed, otherwise else
  block of code will be executed.
                   if … else Syntax
if (this logical expression is true)           NO SEMI-COLON!
{
     statements(s) will be execute if the logical expression is true
}
else               NO SEMI-COLON!
}
    statement(s) will be execute if the logical expression is false
}
• Exercise:
    – Draw flowchart for the syntax above.
If … else statement : Flow Chart
             Test       True
          expression
                False          Statement(s)
         Statement(s)
   if … else : Basic Understanding
If the rain today is worse than the rain yesterday
    I will take my umbrella
else
   I will take my jacket
Then I will go to work
     Exercise:
     • Draw flowchart for the above statement
   if … else : Basic Understanding
If the rain today is worse than
                                  Rain worse than   True
the rain yesterday                   yesterday
    I will take my umbrella
                                         False         Take
else                                                  umbrella
   I will take my jacket
                                  Take jacket
Then I will go to work
                                  Go to work
 if … else statement : Example 1
#include <stdio.h>
int main ()
{
   int num;
   printf (“Enter a number between -10 and 10;”);
   scanf (“%d”, &num);
  if (num >= 0 )
    printf(“%d is a positive number\n”, num);
  else
    printf (“%d is a negative number\n”, num);
return 0;
}                  Exercise:
                   • Draw flowchart for the above code
                   • Predict and display the output
if … else statement : Example 1
        Begin
                                        Enter an integer between -10 and 10:
                                        5
  Read input num
                                        5 is a positive number
                    False
     num>= 0
                                        Enter an integer between 0 and 10:
 True                                   -7
                                        -7 is a negative number
Display “num is a   Display “num is a
positive number”    negative number”
         End
    if … else statement : Example 2
#include <stdio.h>
int main ()
{
  int num;
  printf (“Enter a number you want to check.\n”);
  scanf (“%d”, &num);
  if ((num%2) == 0) /*checking whether remainder is 0 or not*/
   printf (%d is even number.”, num);
  else
   printf (“%d is odd number.”, num);
return 0;
}              Exercise:
               • Draw flowchart for the above code
               • Predict and display the output
if … else statement : Example 2
        Begin
                                     Enter a number you want to check:
                                     5
  Read input num
                                     5 is an odd number
                   False
    num%2==0
                                     Enter a number you want to check:
 True                                8
                                     5 is an even number
 Display “num is   Display “num is
an even number”    an odd number”
         End
  if … else statement : Example 3
#include <stdio.h>
int main ()
{
  int num = 0;
  printf (“Enter a number you want to check.\n”);
  scanf (“%d”, &num);
  if( num < 20 ) /*if condition is true then print the following*/
  {
    printf(“%d is less than 20\n”,num );
    }
  else/* if condition is false then print the following */
    {
      printf(“%d is equal to or greater than 20\n“,num );
    }
return 0;
}                  Exercise:
                  • Draw flowchart for the above code
                  • Predict and display the output
if … else statement : Example 3
        Begin
   Read input                        Enter a number you want to check:
      num
                                     5
                                     5 is less than 20
                  False
    num < 20
 True
Display “num is   Display “num is    Enter a number you want to check:
 less than 20”    greater than 20”   28
                                     28 is greater than 20
         End
    if … else statement : Example 4
• Write flow chart and a C program to determine if the student pass
  or failed based on an average of 2 test marks. The pass marks is 40
  and above.
             If statement : Example 4
• Write a flow chart and C program to determine if the student pass
  based on an average of 2 test marks. The pass marks is 40 and
  above.
                Begin
     Read input test1 and test 2
       Calculate average marks,
         ave= (test1+test2)/2;
                                   False
              Ave >=40
            True
              Display              Display
             “Passed”              “Failed”
                 End
             If statement : Example 4
• Write a flow chart and C program to determine if the student pass
  based on an average of 2 test marks. The pass marks is 40 and
  above.                          #include<stdio.h>
                Begin                         int main()
                                              {
     Read input test1 and test 2                  float test1,test2,ave;
                                                  printf(“Please enter 2 test marks”);
                                                  scanf(“%f %f”,&test1,&test2);
       Calculate average marks,
         ave= (test1+test2)/2;                    ave=(test1+test2)/2;
                                   False          if(ave>=40)
              Ave >=40
                                                    printf(“Passed”);
            True                                  else
              Display              Display          printf(“Failed”);
             “Passed”              “Failed”
                                                  return 0;
                                              }
                 End
Past Year Questions ( Midterm 2016/2017)
Based of the following program segments, compute the value of x when y is 15. x and y are
declared as integer.
 
(i) x = 25;
      if (y != (x – 5))
         x = x – 5;
      else
         x = x / 2;
 
 
 (ii) if ((y < 15) && (y >= 0))
         x = 5 * y;
      else
         x = y % 4;
      Past Year Questions ( Final 2016/2017)
Draw the flowchart base on the pseudocode below.
 
    i    Start
    ii   Read two numbers a, b
    iii c = a + b
    iv if c even number then
               print “even number”
    v    else
               print “odd number”
               repeat step (ii)
    vi End
 
                                   [4 Marks/Markah] 
Multiple Selection : if … else if
• An if…else if control structure shifts
  program control, step by step, through a
  series of statement blocks.
• Is used when program requires more
  than one test expression.
• Very useful to test various conditions
  using single if…else statement.
                 if … else if Syntax
if (test expression1) {
    statements(s) to be execute if test expression1 is true;
   }
else if (test expression2) {
      statement(s) to be execute if test expression1 is false and 2 is true;
    }
else if (test expression3) {
       statement(s) to be execute if test expression1 and 2 are false and 3 is true;
    }
…
…
…
else {
      statements to be executed if all test expressions are false;
  }
Exercise:
 Draw flowchart for the syntax above.
if … else if statement : Flow Chart
       Test          True
    expression               Statement(s)
        1
            False
       Test          True
    expression               Statement(s)
        2
            False
        Test          True
     expression              Statement(s)
         3
             False
    Statement(s)
   if … else if statement : Example 1
#include <stdio.h>
int main(){
  int numb1, numb2;
  printf("Enter two integers for comparison: "\n);
  scanf("%d %d", &numb1,&numb2);
  if(numb1==numb2) //checking whether two integers are equal
     printf("Result: %d = %d",numb1,numb2);
  else if(numb1>numb2) //checking whether numb1 is greater than numb2
     printf("Result: %d > %d",numb1,numb2);
  else
     printf("Result: %d > %d",numb2,numb1);
return 0;
                          Exercise:
 }                        • Draw flowchart for the above code
                          • Predict and display the output
if … else if statement : Example 1
        Begin
Read input numb1 and numb2                    Enter 2 integers for comparison:
                                              7 5
                        True
                                              Result: 7 > 5
      numb1==                     Display
       numb2                   numb1==numb2
                False                         Enter 2 integers for comparison:
                        True
                                              6 10
       numb1>                     Display     Result: 10 > 6
       numb2                   numb1> numb2
             False
       Display                                Enter 2 integers for comparison:
    numb2 > numb1                             4 4
                                              Result: 4 == 4
         End
if … else if statement : Example 2
#include <stdio.h>
int main () {
   char grade;
   printf(“Enter your grade:”);
   scanf(“%c”,&grade):
    if( grade == ‘A’ )
       printf(“Your academic performance is excellent\n" );
    else if( grade == ‘B’ )
       printf(“Your academic performance is good\n" );
    else if( grade == ‘C’ )
       printf(“Your academic performance is satisfactory\n" );
    else
       printf(“Your academic performance is poor\n" );
    return 0;        Exercise:
}                    • Draw flowchart for the above code
                     • Predict and display the output
if … else if statement : Example 2
     Begin
                                                  Enter your grade:
  Read input grade                                A
                                                  Your academic performance is
                     True
                                                  excellent
  Grade==‘A’                Display “Excellent”
             False
                                                  Enter your grade:
                     True
  Grade==‘B’                 Display “Good”       D
             False
                                                  Your academic performance is poor
                     True        Display
  Grade==‘C’
                              “Satisfactory”
                                                  Enter your grade:
             False
                                                  C
  Display “Poor”                                  Your academic performance is
                                                  satisfactory
      End
    if … else if statement : Example 3
•   Write flow chart and a C program to determine if the student pass or failed
    based on an average of 2 test marks. If the average mark is equal to and above
    45, display “Passed”, if the average mark is between 40 and 45, display
    “Conditional Passed” and display “Failed” for marks lower than 40.
    If … else if statement : Example 3
•   Write flow chart and a C program to determine if the student pass or failed
    based on an average of 2 test marks. If the average mark is equal to and above
    45, display “Passed”, if the average mark is between 40 and 45, display
    “Conditional Passed” and display “Failed” for marks lower than 40.
           Begin
Read input test1 and test 2
Calculate average marks,
  ave= (test1+test2)/2;
                                    Display
         Ave >=45
                                   “Passed”
         False
                                    Display
       40 <= Ave < 44         “conditional Passed”
         False
           Display
           “Failed”
             End
    If … else if statement : Example 3
•   Write flow chart and a C program to determine if the student pass or failed
    based on an average of 2 test marks. If the average mark is equal to and above
    45, display “Passed”, if the average mark is between 40 and 45, display
    “Conditional Passed” and display “Failed” for marks lower than 40.
           Begin                                     #include<stdio.h>
                                                     int main()
Read input test1 and test 2
                                                     {
                                                         float test1,test2,ave;
Calculate average marks,                                 printf(“Please enter 2 test marks”)
  ave= (test1+test2)/2;                                  scanf(“%f %f”,&test1,&test2);
                                                          ave=(test1+test2)/2;
                                    Display
         Ave >=45                                         if(ave>=45)
                                   “Passed”
         False                                              printf(“Passed”);
                                    Display                else if(ave>=40 && ave< 45)
       40 <= Ave < 45         “conditional Passed”          printf(“Conditional Passed”);
         False
           Display                                        else
           “Failed”                                         printf(“Failed”);
                                                         return 0;
             End                                     }
    Past Year Questions ( Midterm 2016/2017)
Complete the program below so that it displays the value of n and the message " is positive." if n
is positive. If n is negative, the program should display the value of n and the message "is
negative." If n is zero, the program should produce no output at all. Display the value of n with 2
decimal points.
           #include <stdio.h>
           int main(void)
           {
               double n;
               printf("Enter a number> ");
               scanf("%lf", &n);
               …
               return 0;
           }                          [4 marks]
 
  
 
       Past Year Questions ( Final 2013/2014)
(i) Given the input value for mark is 85, write down the output for both programs in Figure (a) and
Figure (b). Identify which program produces more logical output.
                           Figure (a)                                  Figure (b)
   #include <stdio.h>                            #include <stdio.h>
   int main()                                    int main ()
   {                                             {
     int mark;                                     int mark;
     printf(“Enter student mark:”);                printf (“Enter student mark: ”);
     scanf(“%d”, &mark);                           scanf (“%d”, &mark);
       if (mark >= 80)                               if (mark >= 80)
         printf(“\n Grade A”);                          printf (“\n Grade A”);
       else if(mark >= 70)                            if (mark >= 70)
          printf (“\n Grade B ”);                        printf (“\n Grade B”);
       else if(mark >= 60)                            if (mark >= 60)
          printf(“\n Grade C ”);                        printf (“\n Grade C”);
       else                                           if(mark<60)
          printf(“\n Grade D ”);                        printf (“\n Grade D ”);
       return 0;                                      return 0;
   }                                             }
(ii) Without changing the control structure if to if-else if, suggest another way to improve the
statements in Figure (b), so that an accurate selection can be executed. Write down the improved
version for the selection program segment.
   Compound (Block of ) Statement:
• Any block of the code is written or
  embedded inside the pair of the curly             if (expression)
                                                    {
  braces.                                              StatementA1;
• If condition specified inside the ‘if block’ is      StatementA2;
  true, then statements written inside the             ...
                                                    }
  pair of curly braces will be executed
                                                    else
• If expression evaluates to false, all the         {
  statements between the braces following              StatementB1;
  the else will be executed                            StatementB2;
                                                          ...
• In either case, execution continues with          }
  next statement.
                                                    Next_Statement;
              Compound Statement:
               Basic Understanding
If the weather is sunny,
   I will walk to the park, have a picnic and walk home
else
  I will stay in, watch football and drink coke
Sleep at 10
Exercise:
• Draw flowchart for the above statement
Compound Statement:
 Basic Understanding
                      True
   Weather is sunny
  False
       Stay inFalse      Walk to park
   Watch Football        Have a picnic
     Drink coke              Walk home
          Sleep
                 Compound Statement:
                     Example 1
int main()
{
   int num = 10 ;
     if(num > 0)
     {
     printf ("\nNumber is Positive");
     printf ("\nThis is The Example of Compound Statement");
     }
    return 0;
}
                 Compound Statement:
                     Example 2
#include<stdio.h>
int main()
{
  int Age=18;
     if (Age > 17 )
     {
         printf (“Eligible to take car driving license\n”);
         print (“Allow to register at driving school\n”);
       }
     else
     {
         printf (“Not eligible to drive\n”);
         printf (“Not allows to register at driving school\n”);
     }
    return 0;
}
     Past Year Questions ( Final 2015/2016)
Determine the output values of the program segment in the following Figure.
        int finished = 0, firstInt = 3, secondInt = 20;
        if (secondInt/firstInt <= 2)
            finished++;
        else
        {
            firstInt++;
            secondInt= secondInt-1;
        }
        printf(“%d\n%d\n%d\n”,firstInt,secondInt, finished);