Presentation is loading. Please wait.

Presentation is loading. Please wait.

The if…else Selection Statement

Similar presentations


Presentation on theme: "The if…else Selection Statement"— 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 60 Print “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 Print “B” else If student’s grade is greater than or equal to Print “C” else If student’s grade is greater than or equal to 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(“ 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 The if Selection Statement
if statement is a single-entry/single-exit structure true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: 3 - 4 is true

10 The if…else Selection Statement
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 60 Print “Passed” else Print “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 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 true false print “Failed” print “Passed” grade >= 60

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

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

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

16 Logical Operators Useful as conditions in loops
&& ( 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 false true || false true !false true

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

18 Logical Operators

19 Logical Operators

20 int w = 5, x = 7, y = 9, z = 1; if (x % y > = 2 + w) { z+ +;
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 + +; } 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; 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 if purchase is over 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 if (x > 10) z= z*m; if ( y< 0) p = p *5;
For x=15, y=-5, z=2, p =3 and m=10, find the output of the following code if (x > 10) z= z*m; if ( y< 0) p = p *5; printf(“%d%d”, z, p); else if ( y< 0)

28 Write a program that reads a number in range 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 per hour, semiskilled workers receive L.E an hour, and skilled workers L.E 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
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’: default: } break; exits from statement

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

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
Incorrect letter grade entered. Enter a new grade. D ^Z Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 Program Output

37 int z; z = / 3 * % 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 x and calculates the values of y and z using the following formulas: ,


Download ppt "The if…else Selection Statement"

Similar presentations


Ads by Google