590 likes | 713 Views
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)
E N D
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
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...
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);
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.
Generic Template /*author: suchandsuch */ #include <stdio.h> int main(){ return 0; }
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...”
Variables declared. /*author: suchandsuch */ #include <stdio.h> int main(){ int firstNum, secondNum, result; char oper; return 0; }
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);
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;
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);
/*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; }
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)
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)
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.");
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).
Fix 1: Add { } if(dayOfWeek > 5) { if(sunny) printf("it's a sunny weekend day."); } else printf("it's a weekday.");
Fix 2: Null Statement if(dayOfWeek > 5) if(sunny) printf("it's a sunny weekend day."); else ; else printf("it's a weekday.");
the ? operator • <expr1> ? <expr2> : <expr3> is simply: • if <expr1> then <expr2> else <expr3>
? - 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;
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; }
revisit: if with1choice if (Expression1) Statement1 ;
if-else with 2 choices if (Expression1) Statement1 ; else Statement2;
else if with 3 choices if (Expression1) statement1 ; else if(Expression2) statement2 ; else statement3 ;
else if with 4 choices if (Expression1) statement1 ; else if(Expression2) statement2 ; else if(Expression3) statement3 ; else statement4 ;
Switch: Just a shorthand • alternative to nested if • uses "break;" which works to exit a loop or a switch statement.
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
Recall nested-if if(oper == '+') result = firstNum + secondNum; else if(oper=='-') result = firstNum - secondNum; else if(oper=='*') result = firstNum * secondNum; else result = firstNum / secondNum;
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); }
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"); }
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?
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");
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");
Common Programming Errors - I int main(){ scanf("%d", age); if(18 <= age < 65) printf("your age is between 18 and 65 ) }
Common Programming Errors - II char ch = *; scanf("%c", &ch); switch(ch){ case + : printf("plus sign"); case - : printf("minus sign"); default : printf("undefined"); }
Programming Task: • Read 100 integer values and print out their avearage.
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);
the "sane" solution: • Loops (Döngüler): • for • while • do-while
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
while-loop while(<test>) <statement> • as long as <test> is true: • <statement> is executed. loop-body
(do-while)-loop do { <statement> } while(<test>) • <statement> is executed once. • as long as <test> is true: • <statement> is executed. loop-body
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"
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.
break & continue • break; • exits the loop; • continue; • the control jumps to the "head" of the loop, skipping the rest of the <statement>.
break & continue while(<test>){ ... continue; break; ... }
Rewrite: for using while for ( <expr1> ; <test> ; <expr2>) <statement> <expr1> while(<test>){ <statement> <expr2> }
Rewrite: while using for for ( ; <test> ;) <statement> while(<test>) <statement>
Rewrite: do-while using while do { <statement> } while(<test>) <statement> while(<test>) <statement>