EKT 150 INTRODUCTION TO COMPUTER PROGRAMMING Control Structure

































- Slides: 33

EKT 150 INTRODUCTION TO COMPUTER PROGRAMMING Control Structure: Selection Part II Dr. Nur Hafizah Ghazali hafizahghazali@unimap. edu. m y

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 (expression 1) { Statement A; if (expression 2) Statement B; else Statement C; } else Statement D; Statement E; if (expression 1) { Statement A; if (expression 2) Statement B; if (expression 3) Statement C; } else Statement D; 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 (expression 1) { Statement A; if (expression 2) Statement B; else Statement C; /*Weather is good? */ /*Yes – go out in the garden*/ /*Warm? */ /*Yes – sit in the sun*/ /*No – Sit in the shade*/ } else Statement D; Statement E; /*Weather not god – stay in*/ /*Drink lemonade in any event*/

Example of Nested if – Flow Chart YES Out in the garden YES Sit in sun Is it warm? Is the weather good? NO Sit in shade Drink some lemonade NO Sit Indoors

Nested if – Exercise 1 #include <stdio. h> int main() { int numb 1, numb 2; printf("Enter two integers to checkn"); scanf("%d %d", &numb 1, &numb 2); if(numb 1==numb 2) //checking whether two integers are equal printf("Result: %d = %d", numb 1, numb 2); else { if(numb 1>numb 2) //checking whether numb 1 is greater than numb 2 printf("Result: %d > %d", numb 1, numb 2); else printf("Result: %d > %d", numb 2, numb 1); } return 0; } Exercise: • Draw flowchart for the above code • Predict and display the output

Exercise 1: Nested if Flow Chart Begin Read input numb 1 & numb 2 YES If numb 1 == numb 2 Display numb 1==numb 2 YES Display numb 1 > numb 2 End NO Is numb 1> numb 2? NO Display numb 2 > numb 1

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 hardern"); } else { //mark is equal or above than 60 printf("You passed!n"); } Exercise: } • Draw flowchart for the above code return 0; • Predict and display the output }

Exercise 2: Nested if Flow Chart Begin Read input mark YES NO mark <=10 Display “ You did not study. You failed!” YES Display “ You failed! Study harder” End mark < 60 NO Display “ You passed!”

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 Display “ Cold” temperature <= 10 NO Temperature <= 25 NO YES Display “Mild” Display “Warm” End temperature <= 35 NO Display “Hot”

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() { int mark; printf(“Enter temperature: n”); scanf("%d", &temperature); if (temperature <= 25 ) { if(temperature<=10) printf(“Coldn"); else printf(“Mildn”); } else { if (temperature <=35 ) printf(“Warmn"); else printf(“Hotn"); } return 0; } Enter temperature: 9 Cold Enter temperature: 24 Mild Enter temperature: 34 Warm Enter temperature: 40 Hot

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% discountn”); } else { //calculate new total price with discount 30% totalprice=totalprice*0. 7; printf(“Get 30% discountn”); } } else { //calculate new total price with discount 10% totalprice=totalprice*0. 9; printf(“Get 10% discountn”); } printf(“Total Price = %. 2 f”, 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 ? result 1 : result 2 • If the condition is true, result 1 is returned else result 2 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 n 0, 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 , a = 10; printf( } { b; "Value of b is %dn", (a == 1) ? 20: 30 ); "Value of b is %dn", (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 == case constant 1? True Statement for first case False Is switch expression == case constant 2? False Default statements True Statement for second case

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'; switch(grade) { case 'A' : printf("Excellent!n" ); break; case 'B' : case 'C' : printf("Well donen" ); break; case 'D' : printf("You passedn" ); break; case 'F' : printf("Better try againn" ); break; default : printf("Invalid graden" ); } printf("Your grade is %cn", grade ); return 0; }

Switch Structures : Example 2 int main () { int choice; printf (“ 1. Create a new databasen”); printf (“ 2. Edit a databasen”); printf (3. Delete a databasen”); printf (“ 4. Merge databasen”); printf (“ 5. Exit systemn”); printf (“Choose an option: ”); scanf (“%d”, &choice); switch (choice) { case 1: printf (“Creating…. n”); break; case 2: printf (“Editing…n”); break; case 3: printf (“Deleting…n”); break; case 4: printf (“Merging…n”); break; case 5: printf (“Thank you, Bye. n”); break; default: : printf (“Invalid input!n”); break; } return 0; }

Switch Structures : Example 3 #include <stdio. h> int main() { char o; float num 1, num 2; printf("Select an operator either + or - or * or / n"); scanf("%c", &o); printf("Enter two operands: "); scanf("%f%f", &num 1, &num 2); switch(o) { case '+': printf("%. 1 f + %. 1 f = %. 1 f", num 1, num 2, num 1+num 2); case '-': printf("%. 1 f - %. 1 f = %. 1 f", num 1, num 2, num 1 -num 2); case '*': printf("%. 1 f * %. 1 f = %. 1 f", num 1, num 2, num 1*num 2); case '/': printf("%. 1 f / %. 1 f = %. 1 f", num 1, num 2, num 1/num 2); default: /* If operator is other than +, -, * or /, error message is printf("Error! operator is not correct"); } return 0; } break; shown */

Past Year Questions ( Final 2016/2017) Rewrite the switch statement below as an if-else if statement. switch (program) { case 12: printf("B. Materialn"); break; case 32: printf("M. Metallurgyn"); break; case 56: printf("P. Polymern"); break; default: printf("Player unknownn"); } [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]