Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 03 if-?-switch. loops METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 7, 2002."— Presentation transcript:

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

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| }]typeflagswidthprecisiontype 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 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 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 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 9 || (c%3 == 0) 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 ? : is simply: if then else

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

21 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; }

22 revisit: if with1choice if (Expression1) Statement1 ;

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

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

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

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

27 switch syntax switch ( ) { case : case :... default : } integral unique single constant optional

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

29 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); }

30 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"); }

31 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?

32 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");

33 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");

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

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

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

37 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);

38

39

40 the "sane" solution: Loops (Döngüler): –for –while –do-while

41 for-loop for ( ; ; ) first expr1 is executed. as long as is true: – is executed. loop-body

42 while-loop while( ) as long as is true: – is executed. loop-body

43 (do-while)-loop do { } while( ) is executed once. as long as is true: – is executed. loop-body

44 Loops: What would happen if the 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 never became false? –"infinite loop"

45 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.

46 break & continue break; –exits the loop; continue; –the control jumps to the "head" of the loop, skipping the rest of the.

47 break & continue while( ){... continue; break;... }

48 Rewrite: for using while for ( ; ; ) while( ){ }

49 Rewrite: while using for for ( ; ; ) while( )

50 Rewrite: do-while using while do { } while( ) while( )

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

52 what's missing? int i, a, sum; for(i=0; i<100; i++){ scanf("%d", &a); sum += a; } printf("%f", sum / 100 );

53 Debugging!! often, the development environments you use have Debugging tools (unix: gdb) You can always make use printf to debug your program. –output the values you've read, to make sure you read them correctly. –output the values you calculate, to see to it that you made the calculations correctly.

54 missing link. int i, a, sum; sum = 0; for(i=0; i<100; i++){ scanf("%d", &a); sum += a; } printf("%f", sum / 100.0 );

55

56 Error-checking. Most of our programs, we'll assume the user knows what he/she is doing. If he didn't, we would have to check at every input, that he/she entered what's needed. Even when input is error-free, we may need to check for things like division-by- zero.

57 scanf errors imagine trying to do read an integer: scanf("%d", &num); what if the user enters a string of characters, instead of a number: please enter a number: I'm a bad user, I will not cooperate.

58 scanf errors Solution1: we could always scanf the input character by character and see whether these characters are digits. Solution2: Remember, scanf returns 0 when no fields are assigned. So: if( ! scanf("%d", &num) ){ printf("input error. Exiting the program\n"); exit(2); }

59 exit(int) function break; exits a loop-control. return [ ] ; exits a function. exit(int); exits the program.


Download ppt "Lecture 03 if-?-switch. loops METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 7, 2002."

Similar presentations


Ads by Google