1 / 39

The if … else Selection St atement

Understand the if-else structure & implement compound statements. Learn about syntax, logic errors, and logical expressions in C. Explore examples and pseudocode.

benjaminw
Download Presentation

The if … else Selection St atement

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The if…else Selection Statement • Block: • Compound statements with declarations • Syntax errors • Caught by compiler • Logic errors: • Have their effect at execution time • Non-fatal: program runs, but has incorrect output • Fatal: program exits prematurely

  2. The if Selection Statement • Selection structure: • Used to choose among alternative courses of action • Pseudocode: If student’s grade is greater than or equal to 60Print “Passed” • If condition true • Print statement executed and program goes on to next statement • If false, print statement is ignored and the program goes onto the next statement • Indenting makes programs easier to read • C ignores whitespace characters

  3. The if…else Selection Statement • Compound statement: • Set of statements within a pair of braces • Example: if ( grade >= 60 ) printf( "Passed.\n" ); else { printf( "Failed.\n" ); printf( "You must take this course again.\n" );} • Without the braces, the statement printf( "You must take this course again.\n" ); would be executed automatically

  4. 3.6 The if…else Selection Statement • Pseudocode for a nested if…else statement If student’s grade is greater than or equal to 90 Print “A”else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F”

  5. Control Structures use logical expressions which may include: 6 Relational Operators < <= > >= == != 3 Logical Operators ! && ||

  6. Equality and Relational Operators

  7. Trace int p, d=4, a=20; if ((d==4) && (a>24)) { p=d+a; printf(“ Low Risk \n”);} else { p=a-d; printf(“ Low Risk \n”);} printf(“ the p is = %d”, p);

  8. The if Selection Statement • Pseudocode statement in C: if ( grade >= 60 ) printf( "Passed\n" ); • C code corresponds closely to the pseudocode • Diamond symbol (decision symbol) • Indicates decision is to be made • Contains an expression that can be true or false • Test the condition, follow appropriate path

  9. true false print “Passed” grade >= 60 The if Selection Statement • if statement is a single-entry/single-exit structure A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 istrue

  10. The if…else Selection Statement • if • Only performs an action if the condition is true • if…else • Specifies an action to be performed both when the condition is true and when it is false • Psuedocode: If student’s grade is greater than or equal to 60Print “Passed” elsePrint “Failed” • Note spacing/indentation conventions

  11. The if…else Selection Statement • C code: if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n"); • Ternary conditional operator (?:) • Takes three arguments (condition, value if true, value if false) • Our pseudocode could be written: printf( "%s\n", grade >= 60 ? "Passed" : "Failed" ); • Or it could have been written: grade >= 60 ? printf( “Passed\n” ) : printf( “Failed\n” );

  12. false true print “Passed” print “Failed” grade >= 60 The if…else Selection Statement • Flow chart of the if…else selection statement • Nested if…else statements • Test for multiple cases by placing if…else selection statements inside if…else selection statement • Once condition is met, rest of statements skipped • Deep indentation usually not used in practice

  13. The value that printed is int delta = 0, x = 3; if (x / 2 = = 1) delta = delta + x; x - -; if (x / 2 = = 0) delta = delta + x; x - -; printf (“ % d “ , delta);

  14. Program Output Enter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7

  15. Enter two integers, and I will tell you the relationships they satisfy: 7 77 is equal to 77 is less than or equal to 77 is greater than or equal to 7 Program Output (continued) Enter two integers, and I will tell you the relationships they satisfy: 22 1222 is not equal to 1222 is greater than 1222 is greater than or equal to 12

  16. Logical Operators • && ( logical AND ) • Returns true if both conditions are true • || ( logical OR ) • Returns true if either of its conditions are true • ! ( logical NOT, logical negation ) • Reverses the truth/falsity of its condition • Unary operator, has one operand • Useful as conditions in loops Expression Result true && false falsetrue || false true !false true

  17. What is value of x when y is 15.0? x = 25.0; if (y != (x-10.0) ) x=x-10.0; else x=x / 2.0;

  18. Logical Operators

  19. Logical Operators

  20. What is the value of variable z after the following code is executed? int w = 5, x = 7, y = 9, z = 1; if (x % y > = 2 + w) { z+ +; if (y – 3 * w > = - x) z - -; else z + +; } else { z = - 1; }

  21. What is the value is assigned to x when y is 15.0? if (y < 15.0) if (y>= 0.0) x=5*y; else x = 2*y; else x= 3 * y;

  22. Confusing Equality (==) and Assignment (=) Operators • Dangerous error • Does not ordinarily cause syntax errors • Any expression that produces a value can be used in control structures • Nonzero values are true, zero values are false • Example using ==: if ( payCode == 4 ) printf( "You get a bonus!\n" ); • Checks payCode, if it is 4 then a bonus is awarded

  23. Confusing Equality (==) and Assignment (=) Operators • Example, replacing == with =: if ( payCode = 4 ) printf( "You get a bonus!\n" ); • This sets payCode to 4 • 4 is nonzero, so expression is true, and bonus awarded no matter what the payCode was • Logic error, not a syntax error

  24. Confusing Equality (==) and Assignment (=) Operators • lvalues • Expressions that can appear on the left side of an equation • Their values can be changed, such as variable names • x = 4; • rvalues • Expressions that can only appear on the right side of an equation • Constants, such as numbers • Cannot write 4 = x; • Must write x = 4; • lvalues can be used as rvalues, but not vice versa • y = x;

  25. If--Else for a mail order Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost: • The discount rate is 25% and the shipping is 10.00 if purchase is over 100.00. • Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

  26. Example The Air Force has asked you to write a program to label aircrafts as military or civilian. Your program input is the plane’s speed and its estimated length. For planes traveling faster than 1100 km/hr, you will label those shorter than 52 m “military”, and longer as “Civilian”. For planes traveling less than 1100, you will issue an “aircraft unknown” statement.

  27. Find the output • For x=15, y=-5, z=2, p =3 and m=10, find the output of the following code

  28. Write a program that reads a number in range 0-100 and print ‘F’ if the number is less than 50, ‘P’ if the number is in the range 50-59, and ‘S’ if the number is greater than 65.

  29. Write a complete C program that asks a person for the number of hours he worked in a week and then print out his salary. Given that a person who worked 40 hours or less gets $5 per hour and a person who worked more than 40 hours gets $7 per hour for over 40 hours?

  30. A factory has some workers and it divides its workers into three skill levels. Unskilled workers receive L.E. 8.15 per hour, semiskilled workers receive L.E. 12.55 an hour, and skilled workers L.E. 18.60 an hour. Write a program to calculate the worker’s weekly pay formatted to two decimal places. Your program input should consist of the hours worked and a skill level indicator for the worker. Then the wage should be displayed.

  31. The switch Multiple-Selection Statement • switch • Useful when a variable or expression is tested for all the values it can assume and different actions are taken • Format • Series of case labels and an optional default case switch ( value ){ Case ‘1’: actions Case ‘2’: actions default: actions } • break; exits from statement

  32. default action(s) true false true false . . . true false case a action(s) case b action(s) case z action(s) break break break case z case a case b The switch Multiple-Selection Statement • Flowchart of the switch statement

  33. (Part 1 of 3)

  34. (Part 2 of 3)

  35. (Part 3 of 3)

  36. Enter the letter grades. Enter the EOF character to end input. a b c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 Program Output

  37. int z; • z = 10 + 8 / 3 * 2 + 10 % 3; • switch (z) { • case 23 : printf(“ Very High”); break; • case 21 : printf(“ High “); break; • case 18 : printf(“ Med “); break; • case 15 : printf(“ Low “); break; • case 10 : printf(“ Very Low “); break; • default : printf(“ None “); break; • }

  38. Find the output int x= 5, y= 2; char op = ‘*’; switch (op) { case ‘+’ : x = x+y; case ‘-‘ : x=x- y; break; case ‘*’ : x= x * y ; case ‘/’ : x = x / y; break; default : x =x + 1; break; } printf(“ %d % d”, x , y);

  39. Write a program that reads the value of xand calculates the values of yand zusing the following formulas: ,

More Related