1 / 59

Lecture 03 if-?-switch. loops

Mon July 7, 2002. Lecture 03 if-?-switch. loops. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan. Today:. Output Formatting Homework Solution. AND , OR Dangling-Else problem ? switch loops (for, while, do-while)

abel-abbott
Télécharger la présentation

Lecture 03 if-?-switch. loops

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. Mon July 7, 2002 Lecture 03if-?-switch.loops METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan

  2. Today: • Output Formatting • Homework Solution. • AND , OR • Dangling-Else problem • ? • switch • loops (for, while, do-while) • break & continue • Debugging • Error Checking, exit(2); • IDE's...

  3. Output Formatting • See web for details of printf function. • %[flags] [width] [.precision] [{h|l|I64| }]type float f = 10/3.0; printf("[%%f] = [%f]\n", f); printf("[%%.2f] = [%.2f]\n", f); printf("[%%12.2f] = [%12.2f]\n", f); printf("[%%-12.2f] = [%-12.2f]\n", f); printf("[%%012.2f] = [%012.2f]\n", f);

  4. Homework Solution... • Simple Calculator: Write a program that reads two integers separated with one of the four arithmetic operators, and prints out the result of this arithmetic expression.

  5. Generic Template /*author: suchandsuch */ #include <stdio.h> int main(){ return 0; }

  6. Variables • “I will read a number, a character, and then another number. I shall need storage boxes to put each of the three items that I read.” • “I will have to calculate the result of the expression, I may need another variable keep the result...”

  7. Variables declared. /*author: suchandsuch */ #include <stdio.h> int main(){ int firstNum, secondNum, result; char oper; return 0; }

  8. Reading from Input • “An integer, a character, and then another integer.” • “My scanf statement will look like:” scanf(“%d %c %d”, ...); • “Now I just have to put the variables in place. must not forget the ampersand. must not forget the ampersand...” scanf(“%d %c %d”, &firstNum, &oper, &secondNum);

  9. Evaluating Result • “I have to do a different calculation for each arithmetic sign. So, I must say: if oper is ‘+’ do addition, otherwise if oper is ‘-’, do subtraction, and so on... if(oper == ‘+’) result = firstNum + secondNum; else if(oper==‘-’) result = firstNum – secondNum; else if(oper==‘*’) result = firstNum * secondNum; else result = firstNum / secondNum;

  10. Showing the Result • “I calculated in ‘my mind’ the result of the expression, but I must tell the result to whoever asked me...” printf(“%d %c %d = %d\n”, firstNum, oper, secondNum, result);

  11. /*author: suchandsuch */ #include <stdio.h> int main(){ int firstNum, secondNum, result; char oper; scanf("%d %c %d", &firstNum, &oper, &secondNum); if(oper == '+') result = firstNum + secondNum; else if(oper=='-') result = firstNum - secondNum; else if(oper=='*') result = firstNum * secondNum; else result = firstNum / secondNum; printf("%d %c %d = %d\n", firstNum, oper, secondNum, result); return 0; }

  12. Complex Conditions: AND • AND operation ex1&& ex2 • evaluated to 1 (true) if both parts true (!= 0) • otherwise evaluated to 0 c = 4; c > 3 && c < 5 c < 3 && (c % 2 == 0) c > 3 && c < 9 && (c%3 == 0) c > 3 && c < 9 && (c%2 == 0)

  13. Complex Conditions: OR • OR operation ex1|| ex2 • evaluated to 1 (true) if at least one part true (!= 0) • otherwise evaluated to 0 c = 4; c > 3 || c < 5 c < 3 || (c % 2 == 0) c < 3 || c > 9 || (c%3 == 0) c < 3 || c > 9 || (c%2 == 0)

  14. Dangling Else Problem int dayOfWeek, sunny; printf("enter a number [1-7] for dayofweek : "); scanf("%d", &dayOfWeek); printf("enter 1 if it's sunny, 0 if it's not : "); scanf("%d", &sunny); if(dayOfWeek > 5) if(sunny) printf("it's a sunny weekend."); else printf("it's a weekday.");

  15. How is it a problem? • Each "else" is paired with most recent unmatched if clause. • Note: compiler ignores spaces and indentation (just like in HTML-pages).

  16. Fix 1: Add { } if(dayOfWeek > 5) { if(sunny) printf("it's a sunny weekend day."); } else printf("it's a weekday.");

  17. Fix 2: Null Statement if(dayOfWeek > 5) if(sunny) printf("it's a sunny weekend day."); else ; else printf("it's a weekday.");

  18. the ? operator • <expr1> ? <expr2> : <expr3> is simply: • if <expr1> then <expr2> else <expr3>

  19. ? - example • To assign the maximum of x and y to z: z = (x > y) ? x : y; • which is shorthand to saying: if(x>y) z = x; else z = y;

  20. Reminder for a "statement" • a statement can be simple: x = y * 2; • or compound : enclosed with { }. We will consider the below block of code "a single statement." { x = y * 2; y = 3; }

  21. revisit: if with1choice if (Expression1) Statement1 ;

  22. if-else with 2 choices if (Expression1) Statement1 ; else Statement2;

  23. else if with 3 choices if (Expression1) statement1 ; else if(Expression2) statement2 ; else statement3 ;

  24. else if with 4 choices if (Expression1) statement1 ; else if(Expression2) statement2 ; else if(Expression3) statement3 ; else statement4 ;

  25. Switch: Just a shorthand • alternative to nested if • uses "break;" which works to exit a loop or a switch statement.

  26. switch syntax integral integral unique single constant switch ( <case-selecter-expr> ) { case <label1> : <statement(s)1> case <label2> : <statement(s)2> ... default : <statement(s)N> } optional

  27. Recall nested-if if(oper == '+') result = firstNum + secondNum; else if(oper=='-') result = firstNum - secondNum; else if(oper=='*') result = firstNum * secondNum; else result = firstNum / secondNum;

  28. Rewrite using switch switch (oper){ case '+' : result = firstNum + secondNum; break; case '-' : result = firstNum - secondNum; break; case '*' : result = firstNum * secondNum; break; case '/' : result = firstNum / secondNum; break; default : printf("undefined operation"); exit(2); }

  29. gim'me a break. • if "break;" statement is not used, the execution continues down until a "break;" or the closing bracket "}" of the switch is encountered. switch(2){ case 1 : printf("one"); break; case 2 : printf("two"); case 3 : printf("three"); break; case 4 : printf("four"); }

  30. Comparison: if - switch • switch is typically more efficient in execution, but can't always be used due to its syntax limitations • When is nested-if a better choice?

  31. Example: choosing nested if if((0<=heartrate) && (heartrate <=200)) if(heartrate > 100) printf("too high"); else if(heartrate > 60) printf("normal"); else if(heartrate > 0) printf("too low"); else print("too late");

  32. why not use switch here? • Case labels must be constants. • Consider one range: 61 through 100 How would we represent it? case 100: case 99 : ... case 61 : printf("normal");

  33. Common Programming Errors - I int main(){ scanf("%d", age); if(18 <= age < 65) printf("your age is between 18 and 65 ) }

  34. Common Programming Errors - II char ch = *; scanf("%c", &ch); switch(ch){ case + : printf("plus sign"); case - : printf("minus sign"); default : printf("undefined"); }

  35. Programming Task: • Read 100 integer values and print out their avearage.

  36. Cumbersome Solution: int a1, a2, a3, .... a100; float sum, avg; scanf("%d %d ... %d", &a1, &a2, ..., &a100); sum = a1 + a2 + a3 + ... + a100; avg = sum / 100; printf("average is : ", avg);

  37. the "sane" solution: • Loops (Döngüler): • for • while • do-while

  38. for-loop for ( <expr1> ; <test> ; <expr2>) <statement> • first expr1 is executed. • as long as <test> is true: • <statement> is executed. • <expr2> is executed. loop-body

  39. while-loop while(<test>) <statement> • as long as <test> is true: • <statement> is executed. loop-body

  40. (do-while)-loop do { <statement> } while(<test>) • <statement> is executed once. • as long as <test> is true: • <statement> is executed. loop-body

  41. Loops: <test> • What would happen if the <test> was false when the loop was first encountered? • loop-body would never execute. (except: loop body would execute once for do-while loops) • What would happen if the <test> never became false? • "infinite loop"

  42. Loops: choice of usage. • Which loop-control to use? • they all function the same. • a code written in one can easily be written using another. • the choice is merely out of style & readability concerns. • if loop is based on a counter use for. • else if no-counter: • if execution must be run at least once: do-while. • else, use while.

  43. break & continue • break; • exits the loop; • continue; • the control jumps to the "head" of the loop, skipping the rest of the <statement>.

  44. break & continue while(<test>){ ... continue; break; ... }

  45. Rewrite: for using while for ( <expr1> ; <test> ; <expr2>) <statement> <expr1> while(<test>){ <statement> <expr2> }

  46. Rewrite: while using for for ( ; <test> ;) <statement> while(<test>) <statement>

  47. Rewrite: do-while using while do { <statement> } while(<test>) <statement> while(<test>) <statement>

More Related