1 / 34

Today’s Material

Today’s Material. 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.

Download Presentation

Today’s Material

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. Today’s Material • 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

  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. Start Prompt the user and get the fahrenheit temperature to convert celsius = (fahrenheit-32)/1.8 Print the fahrenheit and celsius degrees End Example C Program • So far our programs consisted of statements all of which are executed in sequence until the end of the program is reached #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); }

  4. Programs with If Statements • 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

  5. Start Prompt the user and get number1 and number2 number1 < number2 ? yes no min = number1 min = number2 max = number2 max = number1 Print min and max End Computing min and max of 2 numbers • Prompt the user and get number1 and number2 • if (number1 < number2) • 2.1. min = number1; • 2.2. max = number2; • else(i.e., number1 >= number2) • 3.1. min = number2; • 3.2. max = number1; • Print min and max

  6. expression Y N statement 1 statement 2 if-else Statement • Allows a program to choose between two alternatives by testing the value of an expression • Syntax: if (expression) statement1; [else statement2;] • If the expression is true (1) statement1 is executed, otherwise statement2 is executed

  7. if-else Examples int 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. block (compound statement) 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 */

  9. Curly Brace Location • The location of curly braces is a matter of style • To the compiler it does not matter int finalGrade; … if(finalGrade >= 45){ printf("Pass!\n"); printf("Congratulations!\n"); } else { printf("Fail!\n"); printf("Better luck next time.\n"); } /* end-else */

  10. Start Prompt the user and get number1 and number2 number1 < number2 ? yes no min = number1 min = number2 max = number2 max = number1 Print min and max End 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);

  11. Execution of the Program(1) DATA 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 b 56 45 ? ? ? min max 45 56 ? ? 45 56 Enter 2 ints: min of 45 and 56 is 45 max of 45 and 56 is 56

  12. Execution of the Program(2) DATA 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 b 22 77 ? ? ? min max 22 77 ? ? 77 22 Enter 2 ints: min of 77 and 22 is 22 max of 77 and 22 is 77

  13. expression Y N statement 1 statement 2 Operator Meaning == equal to != not equal < less than <= less than or equal to > greater than >= greater than or equal to 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 • 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”

  14. Expression Interpretation Value a < b True 1 (a + b) >= c True 1 (b + c) > (a + 5) False 0 c != 3 False 0 b == 2 True 1 Relational Expression Examples • Assume a = 1, b = 2, and c = 3

  15. Flowchart for finding the min of 3 ints(1) Start Prompt the user and get number1, number2 and number3 number1 < number2 ? yes no number2 < number3 ? yes number1 < number3 ? yes no no min = number3 min = number1 min = number2 min = number2 Print min End

  16. Code for finding the min of 3 ints (1) • Problem: Find the minimum of 3 integers 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);

  17. Flowchart for finding the min of 3 ints(2) Start Prompt the user and get number1, number2 and number3 min = number1 yes number2 < min? no min = number2 yes number3 < min? no min = number3 Print min End

  18. Code for finding the min of 3 ints (2) • Problem: Find the minimum of 3 integers /* 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);

  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. Symbol Meaning && AND || OR ! NOT 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

  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':

  22. Expressions using Logical Operators(2) int temp = 75; double rain = 0.35; /* probability */ printf(“warm? %d\n”, temp > 70 && temp < 85); printf(“nice? %d\n”, temp > 70 && rain < 0.4); printf(“hot/cold? %d\n”, temp < 50 || temp > 85); printf(“cloudy? %d\n”, rain > 0.3 && rain < 0.7); warm? 1 nice? 1 hot/cold? 0 cloudy? 1

  23. Expressions using Logical Operators(3) /* 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 */

  24. Precedence Operator Associativity 1 -, ++, -- right 2 *, /, % left 3 +, - left 4 >, >=, <, <= left ==, != left 5 &&, || left 6 7 =, +=, -=, .. right Associativity & Precedence Rules • 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. a = (b >= 0) ? b : -b; a gets the absolute value of b min = (a < b) ? a : b; min gets the minimum of a & b 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:

  29. switchStatement • 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. switchStatement 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 Example • int 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 */

More Related