0% found this document useful (0 votes)
24 views33 pages

Ekt150 Introduction To Computer Programming: Control Structure: Selection Part II

This document discusses selection structures in computer programming, specifically nested if statements and the conditional operator. It provides syntax examples and explanations of nested if statements, where one if statement is placed within another if statement. It also explains the syntax and usage of the conditional operator, which returns one value if a condition is true and another value if the condition is false. Sample code examples applying nested if statements and the conditional operator are presented along with exercises asking the reader to predict output and draw flowcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views33 pages

Ekt150 Introduction To Computer Programming: Control Structure: Selection Part II

This document discusses selection structures in computer programming, specifically nested if statements and the conditional operator. It provides syntax examples and explanations of nested if statements, where one if statement is placed within another if statement. It also explains the syntax and usage of the conditional operator, which returns one value if a condition is true and another value if the condition is false. Sample code examples applying nested if statements and the conditional operator are presented along with exercises asking the reader to predict output and draw flowcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

EKT150 INTRODUCTION TO

COMPUTER PROGRAMMING
Control Structure:
Selection Part II

Dr. Nik Adilah Hanin


[email protected]
Outline
• Continues with Selection Structures
– Nested if
– Conditional Operator
– Switch Structures
Nested if
• Test for multiple cases by placing if…else
statements inside if…else statement
• It is possible to have if within if statement
• When one control statement is within another, it
is said to be nested
Nested if : Syntax Examples
• No specific syntax for nested if
– Depends on the program structure
– Must have correct syntax for each if/ if- else/ if – else if
statement
if (expression1)
if (expression1) {
{ Statement A;
Statement A; if (expression2)
if (expression2) Statement B;
Statement B;
else if (expression3)
Statement C; Statement C;
}
}
else
else
Statement D;
Statement D;
Statement E;
Statement E;
Example of Nested if –
Basic Understanding
If the weather is good,
I will go out in the garden,
And if it’s warm,
I will sit in the sun.
else
I will sit in the shade
else
I will stay indoors
I will then drink some lemonade

Exercise:
• Draw flowchart for the above statement
Example of Nested if –
Syntax

if (expression1) /*Weather is good?*/


{
Statement A; /*Yes – go out in the garden*/
if (expression2) /*Warm?*/
Statement B; /*Yes – sit in the sun*/
else
Statement C; /*No – Sit in the shade*/
}
else
Statement D; /*Weather not god – stay in*/

Statement E; /*Drink lemonade in any event*/


Example of Nested if –
Flow Chart
YES Is the
weather Sit Indoors
Out in the garden good? NO

YES NO
Is it warm?

Sit in sun Sit in shade

Drink some
lemonade
Nested if – Exercise 1
#include <stdio.h>
int main()
{
int numb1, numb2;
printf("Enter two integers to check\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
Exercise 1: Nested if Flow Chart
Begin

Read input numb1 & numb2

NO
YES If numb1 ==
numb2

Display
YES Is numb1> NO
numb1==numb2
numb2?

Display numb1 > Display numb2 >


numb2 numb1

End
Exercise 1 : Nested if Sample Output

Enter 2 integers to check:


7 5
Result: 7 > 5

Enter 2 integers to check:


6 10
Result: 10 > 6

Enter 2 integers to check:


4 4
Result: 4 == 4
Nested if – Exercise 2
#include<stdio.h>
int main()
{
int mark;
printf(“Enter mark:\n”);
scanf("%d",&mark);
if ( mark <= 10 )
{
printf("You did not study.\n");
printf("You failed!\n");
}
else { // mark is 11 and above
if ( mark < 60 ) // mark is between 11 and 60
{
printf("You failed !\n");
printf("Study harder\n");
}
else { //mark is equal or above than 60
printf("You passed!\n");
} Exercise:
}
return 0;
• Draw flowchart for the above code
} • Predict and display the output
Exercise 2: Nested if Flow Chart
Begin

Read input mark

NO
YES
mark <=10

Display “ You did not


YES NO
study. You failed!” mark < 60

Display “ You failed! Display “ You


Study harder” passed!”

End
Exercise 2 : Nested if Sample Output

Enter mark:
75
You passed!

Enter mark:
9
You did not study. You failed!

Enter 2 integers to check:


44
You failed! Study harder
Nested if – Exercise 3
Write a C program according to the following flow chart. Include one sample output of the
program.
Begin

Read input temperature

YES Temperature NO
<= 25

YES temperature NO YES temperature NO


<= 10 <= 35

Display Display Display Display


“ Cold” “Mild” “Warm” “Hot”

End
Nested if – Exercise 3
Write a C program according to the following flow chart. Include one sample output of the
program.
#include<stdio.h>
int main()
Enter temperature:
{
int mark; 9
printf(“Enter temperature:\n”); Cold
scanf("%d",&temperature);
if (temperature <= 25 )
Enter temperature:
{
if(temperature<=10) 24
printf(“Cold\n"); Mild
else
printf(“Mild\n”);
}
Enter temperature:
else { 34
if (temperature <=35 ) Warm
printf(“Warm\n");

else
Enter temperature:
printf(“Hot\n"); 40
} Hot
return 0;
}
Past Year Questions ( Midterm 2014/2015)
Predict and write the output of the program segment in Figure 2(a), given totalprice=1200 and
itemnumber=10.

if(totalprice>=1000)
{
if(itemnumber>10)
{
//calculate new total price with discount 50%
totalprice=totalprice*0.5;
printf(“Get 50% discount\n”);
}
else
{
//calculate new total price with discount 30%
totalprice=totalprice*0.7;
printf(“Get 30% discount\n”);
}
}
else
{
//calculate new total price with discount 10%
totalprice=totalprice*0.9;
printf(“Get 10% discount\n”);
}
 printf(“Total Price = %.2f”,totalprice);
[4 marks]
Conditional Operator ( ? : )
• The conditional operator in C is also
known as ternary operator – because it
has three arguments.
• Evaluates an expression returning a value
if that expression is true and different one
if the expression is evaluated as false
Conditional Operator - Syntax

Condition ? result1 : result2

• If the condition is true, result1 is returned


else result2 is returned
Conditional Operator –
Basic Understanding

c =( c > 0 ) ? 10 : - 10

• If c is greater than 0, value of c will be 10


but, if c is less than n0, value of c will be -10
Conditional Operator –
Example 1
1. 10 == 5 ? 11 : 12
2. 10 ! = 4 ? 4 : 3
3. 12 > 8 ? a : b

Exercise:
• Predict and display the output for above
conditional operator
Conditional Operator –
Example 2
#include <stdio.h>

int main() {
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}

Exercise:
• Predict and display the output for above conditional operator
Conditional Operator –
Example 3
#include <stdio.h>

int main()
{
char feb;
int days;
printf("Enter 1 if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days = (feb==‘1') ? 29:28;
/*If test condition (feb==‘1’) is true, days will be equal to 29. */
/*If test condition (feb==‘1') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);

return 0;
}

Exercise:
• Predict and display the output for above conditional operator
Switch Structures
• Similar to if-else if control structure
• Allows a variable to be tested for equality
against a list of values
• Each value is called a case, and the
variable being switched on is checked for
each switch case.
Switch Structures : Syntax

switch (expression) {
case constant-expression 1:
statement (s);
break;
case constant-expression 2:
statement (s);
break;
.
.
.
default:
statements;
}
Switch Structures : Flow Chart
Is switch
expression == True
Statement for
case first case
constant1?

False

Is switch True
expression == Statement for second
case constant2? case

False
Default statements
Switch Structures : Rules (1)
• The expression used in a switch statement must have
an integral or enumerated type, or be of a class type in
which the class has a single conversion function to an
integral or enumerated type
• Can have any number of case statements within a
switch. Each case is followed by the value to be
compared to and a colon.
• The constant-expression for a case must be the same
data type as the variable in the switch, and it much be
constant or a literal.
Switch Structures : Rules (2)
• When the variable being switched on is equal to a case, the
statements following that case will execute until a break
statement is reached.
• When a break statement is reached, the switch terminates,
and the flow of control jumps to the next line following the
switch statement
• Not every case needs to contain a break. If no break appears,
the flow of control will fall through to subsequent cases until a
break is reached
• Can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing
a task when none of the cases is true. No break is needed in
the default case.
Switch Structures : Example 1
#include <stdio.h>
int main ()
{
char grade = 'B'; case 'D' :
switch(grade) printf("You passed\n" );
{ break;
case 'A' : case 'F' :
printf("Better try again\n" );
printf("Excellent!\n" );
break;
break;
default :
case 'B' : printf("Invalid grade\n" );
case 'C' : }
printf("Well done\n" ); printf("Your grade is %c\n", grade );
break; return 0;
}
Switch Structures : Example 2
int main ()
{ case 3:
int choice; printf (“Deleting…\n”);
printf (“1. Create a new database\n”); break;
printf (“2. Edit a database\n”); case 4:
printf (3. Delete a database\n”); printf (“Merging…\n”);
printf (“4. Merge database\n”); break;
printf (“5. Exit system\n”); case 5:
printf (“Choose an option:”); printf (“Thank you, Bye.\n”);
scanf (“%d”, &choice); break;
switch (choice) { default::
case 1: printf (“Invalid input!\n”);
printf (“Creating….\n”); break;
break; }
case 2: return 0;
printf (“Editing…\n”); }
break;
Switch Structures : Example 3
#include <stdio.h>
int main()
{
char o;
float num1,num2;

printf("Select an operator either + or - or * or / \n");


scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+': printf("%.1f + %.1f = %.1f",num1, num2, num1+num2); break;
case '-': printf("%.1f - %.1f = %.1f",num1, num2, num1-num2); break;
case '*': printf("%.1f * %.1f = %.1f",num1, num2, num1*num2); break;
case '/': printf("%.1f / %.1f = %.1f",num1, num2, num1/num2); break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
}
return 0;
}
Past Year Questions ( Final 2016/2017)
Rewrite the switch statement below as an if-else if statement.
 
switch (program) {
case 12: printf("B. Material\n");
break;
  case 32: printf("M. Metallurgy\n");
break;
  case 56: printf("P. Polymer\n");
break;
  default: printf("Player unknown\n");
}
 
[4 Marks/Markah]
 
Past Year Questions ( Midterm 2016/2017)
Predict the output of the following C segment if the input value beta = 4.

scanf (“%d”,&beta)
switch (beta)
{
case 1:
case 2: beta = beta + 6; break;
case 4: beta--;
case 5: beta = 6 * beta;
case 6: beta = beta + 10; break;
default: beta--;
} (2 marks)
 
Past Year Questions ( Midterm 2015/2016)
Convert the if-else if segment in the following Figure to a switch statement.

if (colour == 1)
printf (“red”);
else if (colour == 2)
printf (“yellow”);
else if (colour == 3)
printf (“green”);
else
printf (“other colours”); [8 Marks/Markah]

You might also like