03 - Selection Part 1
03 - Selection Part 1
COMPUTER PROGRAMMING
Control Structure:
Selection Part I
• 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;
Is it raining?
If the answer yes, take umbrella
Exercise:
• Draw flowchart for the above statement
If statement : Flow Chart
False False
Expression Is it raining
True True
False
Num<10
Enter a number to check:
True 5
Number= 5
Display Num 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
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
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
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;
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
• 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
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);
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
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
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>
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);
return 0;
Exercise:
} • Draw flowchart for the above code
• Predict and display the output
if … else if statement : Example 1
Begin
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):
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
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
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
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
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.
if (secondInt/firstInt <= 2)
finished++;
else
{
firstInt++;
secondInt= secondInt-1;
}
printf(“%d\n%d\n%d\n”,firstInt,secondInt, finished);