1 / 54

Programming

Programming. Control Flow. Sequential Program. Start. int main() { Statement1; Statement2; … StatementN; }. S1. S2. S3. S4. S5. End. Absolute Value. Given a user input we would like to calculate its absolute value. Something along the lines

nardo
Download Presentation

Programming

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. Programming Control Flow

  2. Sequential Program Start int main() { Statement1; Statement2; … StatementN; } S1 S2 S3 S4 S5 End

  3. Absolute Value • Given a user input we would like to calculate its absolute value. • Something along the lines If the number is negative “make it positive” • Notice that we only execute “make it positive” in case the number is negative!

  4. if Statement • Used to conditionally execute a statement or block of statements. if(expression) statement; Expr True False Statement Rest of Program if (grade > 60) printf("Congratulations! You passed"); printf("Your grade is %d", grade);

  5. Operators • In C, every expression has a numeric value • When using arithmetic operators (+, -, *, /) this is straightforward • The value of A+B is the sum of A and B • And so on…

  6. More About Operators • Expressions with relational operators (<, <=, >, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’) • A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B • The exact non-zero value varies (and is not important for that matter)

  7. Relational operators • They are: • A == B (Note the difference from A = B) • A != B • A < B • A > B • A <= B • A >= B • The expression is “false” if it’s value is zero and “true” otherwise

  8. True or False • In C, every expression has a numeric value • An expression is ‘true’ when its value is non-zero • it is false it evaluates to zero. • Therefore, in the following – if (expression)statement statement is executed if expression evaluates to non-zero.

  9. Block • A sequence of statements enclosed within curly braces {} if (grade > 60){ printf("Congratulations! You passed"); printf("Hip Hip Hooray!"); } printf("Your grade is %d", grade);

  10. Example - Absolute Value void main() { double num; printf("Please enter a real number: "); scanf("%lf", &num); if (num < 0) num = -num; printf("The absolute value is %g\n", num); }

  11. if-else Statement False True Expr if(expression) statement1 else statement2 • if expression is true, statement1 is executed. • if expression is false, statement2 is executed • both statements can be (and very often are) replaced by blocks of statements (“compound statements”) Statement2 Statement1 Rest of Program

  12. Example - min int first, second, min; ... if (first < second) { min = first; printf ("The first number is smaller than the second.\n"); } else { min = second; printf ("The second number is smaller than the first\n"); } printf("The smaller number is %d\n", min);

  13. Nested if • The statement in the if statement’s body can be an if statement if(expression)statement if(expression) statement1 else statement2

  14. Example – Nested if-else if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");

  15. Indentation if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); • Misleading indentation • else is associated with the closest if • use {} for clarity and to change the meaning

  16. Indenting if Statements if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");

  17. Indenting if Statements if (x == y){ if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); }

  18. Indenting if Statements if (x == y){ if (y == 0) { printf("x == y == 0"); } else { printf("x == y; x,y != 0"); } }

  19. if-else Statement (cont.) if (x == y) { if (y == 0) printf("x == y == 0"); } else printf("x == y; x,y != 0");

  20. else if • if statements distinguish between exactly 2 cases and execute different code in each case • The else-if construction allows for a multi-way selection

  21. Indenting else if if (expression1) statement1 else if(expression2) statement2 elseif(expression3) statement3 else statement4

  22. Example if (grade >= 90) { printf ("A\n"); } elseif (grade >= 80) { printf ("B\n"); } elseif (grade >= 70) { printf ("C\n"); } elseif (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); }

  23. Example – Different Indentation if (grade >= 90){ printf ("A\n"); } else{if (grade >= 80) { printf ("B\n"); }else {if (grade >= 70) { printf ("C\n"); } else {if (grade >= 60) { printf ("D\n"); }else { printf ("F\n"); } } }}

  24. Example int a, b; printf("Enter two numbers\n"); scanf("%d%d", &a, &b); if (a == b) { printf("The numbers equal %d\n", a); printf("The expression a == b is %d\n", a == b); } else { printf("The numbers are not equal\n"); printf("The expression a == b is %d\n", a == b); } some non-zero value 0

  25. Assignment Expression <variable> = <expression> • Assignment expressions have a value. • It is the value of the right-hand-side expression • For example: (x = 4) evaluates to 4 x = y = z = 0 ( ) ( )

  26. A Common Error • Confusing between the equality and assignment operators • we wanted if (x == 4) … • we wrote if (x = 4) …

  27. Example void main() { int i = 2; printf("i = %d\n", i); printf("(i==4) = %d\n", i==4); printf("i = %d\n", i); printf("(i=4) = %d\n", i=4); printf("i = %d\n", i); } i = 2 (i==4) = 0 i = 2 (i=4) = 4 i = 4

  28. Rule of Thumb • When comparing to a constant it is better to write the constant first • how does this help us? • (4 == i) is the same as (i == 4) BUT(4 = i) is a compilation error

  29. Logical Operators • !A – ‘not’ - True when A is false, and vice versa. • A && B – ‘and’ - True when both A and B are true • A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true

  30. Logical Operators • ! - not • !<expr>, negate the value of the expression. • && - and • <expr1> && <expr2>, True when both expressions are true • || - or • <expr1> || <expr2>, True when at least one of the expressions is true

  31. Truth Tables OR AND NOT

  32. Compound Expressions • Expressions can be combined using logical operators • If we want to check that a value is within a rangeInstead of :Write: if (grade >= 55)if (grade < 60) {/* recheck the exam */} if (grade >= 55 && grade < 60){/* recheck the exam */}

  33. Compound Expressions • Do something if a char is A, C, G or TInstead of:You can write: if (c == 'A') {/* do something */ } elseif (c == 'C') {/* it’s the same thing as before */ } elseif (c == 'G') {/* write it again? */ } elseif (c == 'T') { /* not again!!! */ } if (c == 'A' || c == 'C' || c == 'G' || c == 'T') { /* do something */ }

  34. Revisiting main • Programs are executed in an environment • Upon termination a termination status should be passed to the environment void main() { ... } int main() { ... return 0; }

  35. return Statement return <expression> • Terminates the program (for now) • Return the value of <expression> to the environment • For now: • 1 – an error occurred • 0 – program terminated without errors.

  36. Validating Input • When getting input from the user, it is highly recommended to check whether it is valid. • If it’s not, you should display an appropriate message and return a non-zero value. • For example – if (grade < 0 || grade > 100) { printf(“Invalid grade!\n”); return 1; }

  37. Error!! All is well A silly example int main(void) { int grade; printf("Please enter your grade: "); scanf("%d", &grade); if (grade < 0 || grade > 100) { printf("This is not a valid grade!\n");return 1; } printf("This is indeed a grade.\n"); return 0; }

  38. Exercise • Read a single letter from the user • Make sure the input is valid • In case the letter is lowercase convert to uppercase.In case the letter is uppercase convert to lowercase.

  39. Solution int main() { char c; printf("Please enter aletter: "); scanf("%c", &c); if (c >= 'a' && c <= 'z') printf("%c in uppercase is %c\n", c, c-'a'+'A'); else if (c >= 'A' && c <= 'Z') printf("%c in lowercase is %c\n", c, c-'A'+'a'); else { printf("%c is not aletter!\n", c); return 1; } return 0; }

  40. The conditional operator expr1 ? expr2 : expr3 • This is an expression. It has a value! • If expr1 is True (non-zero), expr2 is evaluated; otherwise expr3 is evaluated

  41. The conditional operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = (i < j) ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

  42. ?: vs. if int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); if (i < j) min = i;else min = j;printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

  43. The ?: operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); printf("The minimum between %d and %d is %d\n", i, j, (i < j)? i : j); return 0; }

  44. The switch statement • A multi-way conditional statement • similar to if-else..if-else • allows the selection of an arbitrary number of choices based on an integer value switch (expression) { case int-const-expr: statement break; case int-const-expr: statement break; … default: statement }

  45. The switch statement • expression must have an integer value (char, int) • when the switch statement is executed: • the expression is evaluated • if a case matches the value of the expression, the program jumps to the first statement after that case label • otherwise, the default case is selected • the default is optional

  46. That grade example again switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); break; case 7: printf ("C\n"); break; case 6: printf ("D\n"); break; default: printf ("F\n"); }

  47. Give me a break • when the switch transfers to the chosen case, it starts executing statements at that point • it will “fall through” to the next case unless you “break out” • break causes the program to immediately jump to the next statement after the switch

  48. What will it print? • Given your ID return the test score int id, score;...switch (id) {case 1: score = 90;case 2: score = 100;case 3: score = 87;default: score = 0;}printf(“Your test score is %d\n“, score);

  49. Without break if (id == 1) jump to a;if (id == 2) jump to b;if (id == 3) jump to c;jump to d;score = 90;score = 100;score = 87;score = 0; a:b:c:d:end: Code executes sequentially

  50. With break if (id == 1) jump to a;if (id == 2) jump to b;if (id == 3) jump to c;jump to d;score = 90;jump to endscore = 100;jump to endscore = 87;jump to endscore = 0; a:b:c:d:end:

More Related