1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the...

Preview:

Citation preview

1

• If statement and relational operators– <, <=, >, >=, ==, !=

• Finding min/max of 2 numbers• Finding the min of 3 numbers• Forming Complex relational expressions

– Logical Operators (!, &&, ||)

• Cascaded if statement• Conditional Operator• switch statement

Today’s Material

2

Generic C Program Structure#include <stdio.h>

/* main designates the starting place of our program */main() { /* Variables hold Data Items Needed in the Program */ Variable Declarations;

/* Steps of our program: I/O, computation (expressions) */ Statement1; Statement2; …

StatementN; } /* end-of-the program */

3

Example C Program

#include <stdio.h>

/* Convert fahrenheit to celsius */main() { float fahrenheit, celsius;

printf(“Enter a temp in fahrenheit: “); scanf(“%f”, &fahrenheit);

celsius = (fahrenheit-32)/1.8;

printf(“%f degrees fahrenheit equals %f degrees celsius\n”, fahrenheit, celsius);

}

Prompt the user and get the fahrenheit temperature to convert

celsius = (fahrenheit-32)/1.8

Print the fahrenheit and celsius degrees

StartStart

EndEnd

• So far our programs consisted of statements all of which are executed in sequence until the end of the program is reached

4

• What about programs which need to select between two alternative set of statements?– You make a comparison and execute a different

set of statement depending on the outcome of the comparison

– Recall our examples with “if” statements– We will consider the problem of computing

min/max of 2 numbers next

Programs with If Statements

5

Computing min and max of 2 numbers

Prompt the user and get number1 and number2

Print min and max

number1 < number2 ?

min = number1

yes

max = number2

min = number2

max = number1

no

StartStart

EndEnd

1. Prompt the user and get number1 and number2

2. if (number1 < number2)– 2.1. min = number1;– 2.2. max = number2;

3. else (i.e., number1 >= number2)– 3.1. min = number2;– 3.2. max = number1;

4. Print min and max

6

if-else Statement• Allows a program to choose between two

alternatives by testing the value of an expression• Syntax:

if (expression)statement1;

[elsestatement2;]

• If the expression is true (1) statement1 is executed, otherwise statement2 is executed

expressionexpression YY

NN

statement 1statement 1statement 2statement 2

7

if-else Examplesint finalGrade;

printf(“Please enter the final grade: “);scanf(“%d”, &finalGrade);if (finalGrade >= 45) printf("Pass \n");

int finalGrade;

printf(“Please enter the final grade: “);scanf(“%d”, &finalGrade);if (finalGrade >= 45) printf("Pass!\n");else printf("Fail!\n");

8

What if I need to execute more than one statement?

int finalGrade;…if(finalGrade >= 45){ printf("Pass!\n"); printf("Congratulations!\n");}else{ printf("Fail!\n"); printf("Better luck next time.\n");} /* end-else */

blockblock(compound(compoundstatement)statement)

9

Curly Brace Location

int finalGrade;…if(finalGrade >= 45){ printf("Pass!\n"); printf("Congratulations!\n");} else { printf("Fail!\n"); printf("Better luck next time.\n");} /* end-else */

• The location of curly braces is a matter of style– To the compiler it does not matter

10

Finding the min and max of 2 ints

int a, b;int min, max;

printf(“Enter 2 ints: “);scanf(“%d%d”, &a, &b);

if (a < b) { min = a; max = b;} else { min = b; max = a;} /* end-else */

printf(“min of %d and %d is %d\n”, a, b, min);

printf(“max of %d and %d is %d\n”, a, b, max);

Prompt the user and get number1 and number2

Print min and max

number1 < number2 ?

min = number1

yes

max = number2

min = number2

max = number1

no

StartStart

EndEnd

11

Execution of the Program(1)int a, b;int min, max;

printf(“Enter 2 ints: “);scanf(“%d%d”, &a, &b);

if (a < b) { min = a; max = b;} else { min = b; max = a;} /* end-else */

printf(“min of %d and %d is %d\n”, a, b, min);

printf(“max of %d and %d is %d\n”, a, b, max);

?

a

?min

DATA

?45

45

?b

56

?max56

Enter 2 ints:min of 45 and 56 is 45max of 45 and 56 is 56

45 56

12

Execution of the Program(2)int a, b;int min, max;

printf(“Enter 2 ints: “);scanf(“%d%d”, &a, &b);

if (a < b) { min = a; max = b;} else { min = b; max = a;} /* end-else */

printf(“min of %d and %d is %d\n”, a, b, min);

printf(“max of %d and %d is %d\n”, a, b, max);

?

a

?min

DATA

?77

22

?b

22

?max77

Enter 2 ints:min of 77 and 22 is 22max of 77 and 22 is 77

77 22

13

Relational Expression in if Statement

• Expression in if statement compares two values and produces either True (1) or False (0)– Called a relational expression– Formed using relational operators

greater than or equal to>=

greater than>

less than or equal to<=

less than<

not equal!=

equal to==

MeaningOperator

• C does not have an explicit boolean type– So integers are used instead. The general rules

is:– “Zero is false, any non-zero value is true”

expressionexpression YY

NN

statement 1statement 1statement 2statement 2

14

Relational Expression Examples

• Assume a = 1, b = 2, and c = 3

1Trueb == 2

0Falsec != 3

0False(b + c) > (a + 5)

1True(a + b) >= c

1Truea < b

ValueInterpretationExpression

15

Flowchart for finding the min of 3 ints(1)

Prompt the user and get number1, number2 and number3

number1 < number2 ?yes

StartStart

number1 < number3 ?number2 < number3 ?

min = number2min = number3

no

min = number1 min = number2

yes yes

no no

Print min

EndEnd

16

Code for finding the min of 3 ints (1)

int a, b, c; int min;

printf(“Enter 3 ints: “);scanf(“%d%d%d”, &a, &b, &c);

if (a < b){ if (a < c) min = a; else min = c; } else { if (b < c) min = b; else min = c;} /* end-else */

printf(“Min of %d, %d, %d is %d\n”, a, b, c, min);

• Problem: Find the minimum of 3 integers

17

Flowchart for finding the min of 3 ints(2)

Prompt the user and get number1, number2 and number3

number2 < min?

StartStart

no

min = number1

min = number2

yes

number3 < min?

no min = number3

yes

Print min

EndEnd

18

Code for finding the min of 3 ints (2)

/* Here is a simpler alternative implementation */int a, b, c; int min;

printf(“Enter 3 ints: “);scanf(“%d%d%d”, &a, &b, &c);

min = a; /* Assume that a is the minimum */if (b < min) min = b; /* Is b smaller? */if (c < min) min = c; /* Is c smaller? */

printf(“Min of %d, %d, %d is %d\n”, a, b, c, min);

• Problem: Find the minimum of 3 integers

19

The need for Logical Operators• In certain cases, you may want to form more

complex relational expressions– (x is equal to 5) OR (x is equal to 8)

• (x == 5) OR (x == 8)

– (x is greater than 5) AND (x is less than 10)• (x > 5) AND (x < 10)

– (x is less than y) AND (y is not equal to 20)• (x < y) AND (y != 20)

• C provides 3 logical operators to form such complex relational expressions– AND (&&), OR (||), NOT (!)

20

Logical Operators• Used to combine relational expressions that

are either True (1) or False (0)– Using logical operators you can form complex

relational expressions and use them inside if statements

&&(AND)

0(False)

1(True)

0 0 0

1 0 1

NOT!

OR||

AND&&

MeaningSymbol

||(OR)

0(False)

1(True)

0 0 1

1 1 1

21

Expressions using Logical Operators(1)

• Suppose that a is an integer variable whose value is 7 and ch is a character variable holding the character 'q':

Expression Interpretation Value

(a >= 6) && ( ch == 'q') True 1

(a >= 6) || ( ch == 'A') True 1

(a >= 6) && ( ch == 'A') False 0

22

Expressions using Logical Operators(2)

int temp = 75;int temp = 75;double rain = 0.35; /* probability */double rain = 0.35; /* probability */

printf(“warm? %d\n”, temp > 70 && temp < 85);printf(“warm? %d\n”, temp > 70 && temp < 85);printf(“nice? %d\n”, temp > 70 && rain < 0.4);printf(“nice? %d\n”, temp > 70 && rain < 0.4);printf(“hot/cold? %d\n”, temp < 50 || temp > 85);printf(“hot/cold? %d\n”, temp < 50 || temp > 85);printf(“cloudy? %d\n”, rain > 0.3 && rain < 0.7);printf(“cloudy? %d\n”, rain > 0.3 && rain < 0.7);

warm? 1nice? 1hot/cold? 0cloudy? 1

23

/* If a equals 4 OR a equals 10 */if (a == 4 || a == 10){ ...} else { ...} /* end-else */

/* x is in between 2 AND 20 */if (x >= 2 && x <= 20){ ...} /* end-if */

/* y is greater than 20 AND x is NOT equal to 30 */if (y > 20 && x != 30){ ...} /* end-if */

Expressions using Logical Operators(3)

24

Associativity & Precedence Rules

left>, >=, <, <=4

left+, -3

left*, /, %2

right -, ++, --1

AssociativityOperatorPrecedence

5

6

7

==, !=

&&, ||

=, +=, -=, ..

left

left

right

• Here is the associativity and precedence rules for all operators provided by C

• Again, the best thing to do is to parenthesize the expression to avoid ambiguity

25

Cascaded If Statements• We often need to test a series of conditions stopping

as soon as one of them is true– E.g. We want to test whether “n” is equal to 0, less than 0 or

greater than 0

if (n < 0) printf(“n < 0\n”);else { if (n == 0) printf(“n == 0\n”); else printf(“n > 0\n”);} /* end-else */

• Instead of nesting the second if statement inside the else, we often write it as follows, called the cascaded if

if (n < 0) printf(“n < 0\n”);else if (n == 0) printf(“n == 0\n”);else printf(“n > 0\n”);

26

Cascaded if Syntax

if (expression1)statement1;

[else if (expression2) statement2;

else if (expression3) statement3;

… else

statementN;]

27

Cascaded if Example

int finalGrade;…if (finalGrade >= 90)

printf(“Passed: Your grade is A \n”);else if (finalGrade >= 85)

printf(“Passed: Your grade is A- \n”);else if (finalGrade >= 80)

printf(“Passed: Your grade is B+ \n”);else if (finalGrade >= 75)

printf(“Passed: Your grade is B \n”);else if (finalGrade >= 70)

printf(“Passed: Your grade is B- \n”);else if (finalGrade >= 55)

printf(“Passed: Your grade is C \n”);else

printf(“Failed \n”);

28

Conditional Operator• You will encounter statements of the

following sort in many place in your code:

if (expression) statement1;

else statement2;

• There is a shorter way to write such statements using the tertiary conditional operator– condition ? expr1 : expr2

• Examples:

a = (b >= 0) ? b : -b; a gets the absolute value of b

min = (a < b) ? a : b; min gets the minimum of a & b

29

switch Statement• Often we need to compare an expression against a

series of values to see which one matches– We can implement such code using cascaded if as follows

if (grade == 5) printf(“Excellent\n”);else if (grade == 4) printf(“Good\n”);else if (grade == 3) printf(“Pass\n”);else if (grade == 2) printf(“Poor\n”);else if (grade == 1) printf(“Fail\n”);else printf(“Illegal grade\n”);

• As an alternative to this kind of cascaded if, C provides the “switch” statement

30

switch Statement Example• Here is the re-implementation of the previous

cascaded if statements using the switch statement

switch(grade){ case 5: printf(“Excellent\n”); break; case 4: printf(“Good); break; case 3: printf(“Pass\n”);

break; case 2: printf(“Poor\n”); break; case 1: printf(“Fail\n”); break; default: printf(“Illegal grade\n”); break;} /* end-switch */

31

switch Statement Syntax• Selects a sequence of one or more instructions

based on the result of comparing the value of an expression to a specific value

switch(expression) {case value1:

statement1;…[break;]

case value2:statement2;

…[break;]

default:statementN;

…[break;]

} /* end-switch */

32

Another switch Exampleint main(){

char operator;int a, b;

printf(“Enter an expression: “); scanf(“%d%c%d”, &a, &operator, &c);

switch(operator) {case ‘+’:

printf(“%d+%d = %d\n”, a, b, a+b);break;

case ‘-’:

printf(“%d-%d = %d\n”, a, b, a-b);break;

case ‘*’: printf(“%d*%d = %d\n”, a, b, a*b);

break;case ‘/’:

if(value == 0) {printf(“Error: Divide by zero \n”);printf(“ Operation ignored \n”);

} else printf(“%d/%d = %d\n”, a, b, a/b);

break;default:

printf(“Unknown operator \n”);break;

} /* end-switch */

return 0;} /* end-main */

33

The role of break inside switch • Notice that “break” takes us out of the switch

statement• If break is omitted after a case, the control

continues with the first statement of the next case

switch(grade){ case 5: printf(“Excellent\n”); case 4: printf(“Good); case 3: printf(“Pass\n”); case 2: printf(“Poor\n”); case 1: printf(“Fail\n”); default: printf(“Illegal grade\n”);} /* end-switch */

• If grade == 3, this will print– Pass Poor Fail Illegal grade

34

The role of break inside switch• Falling through the case may be what is

really intended in your code.– If that’s the case, put a comment for your own

benefit

• Example:

switch(grade){ case 5: case 4: case 3: case 2: num_passing++; /* Fall through */ case 1: num_total++; break;} /* end-switch */

Recommended