Introduction to Programming ( 數 ) Lecture 4 Spring 2005 March 11, 2005 Topics Review of if statement The switch statement Repetition and Loop Statements For-Loop Condition-Loop Reading: Chap. 5.7~ Chap. 6 1
Review: if (if-else statements) if-else if (expr) Statement1; else Statement2; if-else 流 false expr true Statement2 Statement1 int main() int num; Use Logical Operators printf("please input a number between 1 to 100 : "); scanf("%d", &num); if (num >= 1) if (num <= 100) //nested if printf("valid number %d\n",num); else printf("invalid number %d\n",num); else printf("invalid number %d\n",num); printf("bye Bye!\n"); system("pause"); return 0; If ((num >= 1) && (num <= 100)) 2
NESTED IF with relational op if (( time >= 0) && (time < 12)) printf( Good Morning ); else if ((time >= 12) && (time < 18)) printf( Good Afternoon ); else if ((time >= 18) && (time < 24.)) printf( Good Evening ); else printf( Time is out of range ); NESTED IF with logical op if ( x == 5 ) if ( y == 5 ) printf ( Both are 5. \n ) ; else printf ( x is 5, but y is not. \n ) ; else if ( y == 5 ) printf ( y is 5, but x is not. \n ) ; else printf ( Neither is 5. \n ) ; Income Tax Example income < 15,000 < 15,000 15,000, < 30,000 30,000, < 50,000 50,000, < 100,000 100,000 tax 0% 18% 22% 28% 31% if ( income < 15000 ) printf( No tax. ); if ( income >= 15000 && income < 30000 ) printf( 18%% tax. ); if ( income >= 30000 && income < 50000 ) printf( 22%% tax. ); if ( income >= 50000 && income < 100000 ) printf( 28%% tax. ); if ( income >=100000) printf( 31%% tax. ); 3
Cascaded ifs if ( income < 15000 ) if ( income < 15000 ) printf( No tax ); printf( No tax ); else else if ( income < 30000 ) if ( income < 30000 ) printf( 18%% tax. ); printf( 18%% tax. ); else if ( income < 50000 ) else printf( 22%% tax. ); if ( income < 50000 ) else if ( income < 100000 ) printf( 22%% tax. ); printf( 28%% tax. ); else else if ( income < 100000 ) printf( 31%% tax. ); printf( 28%% tax. ); else printf( 31%% tax. ); Order is important. Conditions are evaluated in order given. DeMorgan s Laws DeMorgan s laws help determine when two complex conditions are equivalent They state:! ( P && Q ) is equivalent to (!P!Q )! ( P Q ) is equivalent to (!P &&!Q ) This applies for any Boolean expressions P and Q, which might themselves be complex expressions if (! (age < 25 && sex == M ) ) printf ( Cheap rates. \n ) ; is equivalent to (?) if ( age >= 25 sex!= M ) ) printf ( Cheap rates. \n ) ; 4
Gotcha! = versus == int a = 2 ; (C Has No Boolean values) if ( a = 1 ) /* semantic (logic) error! */ printf ( a is one\n ) ; else if ( a == 2 ) printf ( a is two\n ) ; else printf ( a is %d\n, a) ; Multiple Selection So far, we have only seen binary selection. if ( age >= 18 ) printf( Vote!\n ) ; if ( age >= 18 ) printf( Vote!\n ) ; else printf( Maybe next time!\n ) ; 5
練 3 數 流 流 6
狀 if 3 數 狀 if 3 數 7
狀 if 3 數 狀 if 3 數 8
行 Multiple Selection (con t) Sometimes it is necessary to branch in more than two directions. We do this via multiple selection. The multiple selection mechanism in C is the switch statement. 9
Multiple Selection with if if (day == 0 ) printf ( Sunday ) ; if (day == 1 ) printf ( Monday ) ; if (day == 2) printf ( Tuesday ) ; if (day == 3) printf ( Wednesday ) ; (continued) if (day == 4) printf ( Thursday ) ; if (day == 5) printf ( Friday ) ; if (day == 6) printf ( Saturday ) ; if ((day < 0) (day > 6)) printf( Error - invalid day.\n ) ; Multiple Selection with if-else if (day == 0 ) printf ( Sunday ) ; else if (day == 1 ) printf ( Monday ) ; else if (day == 2) printf ( Tuesday ) ; else if (day == 3) printf ( Wednesday ) ; else if (day == 4) printf ( Thursday ) ; else if (day == 5) printf ( Friday ) ; else if (day == 6) printf ( Saturday ) ; else printf ( Error - invalid day.\n ) ; This if-else structure is more efficient than the corresponding if structure. Why? 10
The switch Multiple-Selection Structure switch ( integer expression ) case constant 1 : statement(s) break ; case constant 2 : statement(s) break ;... default: statement(s) break ; switch Example switch ( day ) case 0: printf ( Sunday\n ) ; break ; case 1: printf ( Monday\n ) ; break ; case 2: printf ( Tuesday\n ) ; break ; case 3: printf ( Wednesday\n ) ; break ; case 4: printf ( Thursday\n ) ; break ; case 5: printf ( Friday\n ) ; break ; case 6: printf ( Saturday\n ) ; break ; default: printf ( Error -- invalid day.\n ) ; break ; Is this structure more efficient than the equivalent nested if-else structure? 11
switch Statement Details The last statement of each case in the switch should almost always be a break. The break causes program control to jump to the closing brace of the switch structure. Without the break, the code flows into the next case. This is almost never what you want. A switch statement will compile without a default case, but always consider using one. Include a default case to catch invalid data. Inform the user of the type of error that has occurred (e.g., Error - invalid day. ). A Different Switch Example #include <stdio.h> int main(void) int mo; scanf("%d", &mo); /* get month number from user */ switch (mo) case 2: printf("28 day month"); break; case 4: /* 30 days hath sep, apr, jun, nov */ case 6: case 9: case 11: printf("30 day month"); break; default: printf("31 day month"); break; return 0; 12
Why Use a switch Statement? A nested if-else structure is just as efficient as a switch statement. However, a switch statement may be easier to read. Also, it is easier to add new cases to a switch statement than to a nested if-else structure. The char Data Type The char data type holds a single character. char ch; Example assignments: char grade, symbol; grade = B ; symbol = $ ; The char is held as a one-byte integer in memory. The ASCII code is what is actually stored, so we can use them as characters or integers, depending on our need. 13
The char Data Type (con t) Use scanf ( %c, &ch) ; to read a single character into the variable ch. (Note that the variable does not have to be called ch. ) Use printf( %c, ch) ; to display the value of a character variable. #include <stdio.h> int main ( ) char ch ; char Example printf ( Enter a character: ) ; scanf ( %c, &ch) ; printf ( The value of %c is %d.\n, ch, ch) ; return 0 ; If the user entered an A, the output would be: The value of A is 65. 14
switch statement with chars Example: switch (c) case '+' : i = i+2; break; case '-' : i = i-2; break; case '*' : i = i*2; break; case '/' : i = i/2; break; default: i = 0; switch statement ---- 例 int main() char grade; printf( Input grade : "); scanf("%c", &grade); switch (grade) case a : case A : printf( Excellent \n ); break; case b : case B : printf( Good \n ); break; case c : case C : printf( Be study hard \n ); break; default : printf( Failed\n ); return 0; 15
例 switch statement 力 類 度 度 度 度 契 力 度 度 度 度 度 類 度數 switch statement 例 2 流 類 / / Yes 度數 No 列 類 契 0~300 度 /301 度 力 C 0~300 度 /301 度 300 度 301 度 300 度 301 度 = 度數 *3.3 =300*3.3+ ( 度數 -300)*4.2 = 度數 *(1.9) +150*C = 度數 *6 =300*6+ ( 度數 -300)*6.8 16
switch statement 例 2 () 類 類 度數 契 力 if (T>=1 && T<=3) printf(" 度數 = "); scanf("%f", &Deg); /* */ Ch2_1_2.c switch statement 例 2 switch(t) case 1: if (Deg<=100) Fee = Deg*3.3; else Fee = (Deg-300)*4.2 + 300*3.3; break; case 2: printf(" 契 力 = "); scanf("%f", &C); Fee = C*150 + Deg*1.9; break; case 3: if (Deg<=300) Fee = Deg*6; else Fee = (Deg-300)*6.8 + 300*6; break; 17
例 2 switch statement printf(" %f", Fee); printf("\n"); else printf(" 類!"); printf("\n"); 練 if switch 流 18
if switch if switch 19
if switch if switch 20
if switch if switch 21
if switch 行 22
Repetition Statements (Repetition statements, Loop, Iteration ): ( ) 行 C Loop statements for loop: (Counting loop) while loop: (Condition loop) do-while loop: (Condition loop) Reading: Chap. 5 while loop Syntax for while loop while ( expr ) statements; next-statements; Condition: true of false expr: children = 7; cookies = 1; while ( children > 0 ) children = children - 1 ; cookies = cookies * 2 ; 23
while loop Flow chart for while loop expr false true statements Note: C has no boolean value; C uses int for boolean values 0 for false and non-zero for true next-statements while Loop: Example 1 Problem: Write a program that calculates the average exam grade for a class of 10 (or n) students. What are the program inputs? the exam grades What are the program outputs? the average exam grade 24
The Pseudocode <total> = 0 <grade_counter> = 1 // 錄 數 While (<grade_counter> <= 10) Display Enter a grade: Read <grade> <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 End_while <average> = <total> / 10 Display Class average is:, <average> #include <stdio.h> int main ( ) int counter, grade, total, average ; total = 0 ; counter = 1 ; while ( counter <= 10 ) printf ( Enter a grade : ) ; scanf ( %d, &grade) ; The C Code total = total + grade ; counter = counter + 1 ; average = total / 10 ; printf ( Class average is: %d\n, average) ; return 0 ; 25
Versatile? How versatile is this program? It only works with class sizes of 10. We would like it to work with any class size. A better way : Ask the user how many students are in the class. Use that number in the condition of the while loop and when computing the average. <total> = 0 <grade_counter> = 1 New Pseudocode Display Enter the number of students: Read <num_students> While (<grade_counter> <= <num_students>) Display Enter a grade: Read <grade> <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 End_while <average> = <total> / <num_students> Display Class average is:, <average> 26
New C Code #include <stdio.h> int main ( ) int numstudents, counter, grade, total, average ; total = 0 ; counter = 1 ; printf ( Enter the number of students: ) ; scanf ( %d, &numstudents) ; while ( counter <= numstudents) printf ( Enter a grade : ) ; scanf ( %d, &grade) ; total = total + grade ; counter = counter + 1 ; average = total / numstudents ; printf ( Class average is: %d\n, average) ; return 0 ; Why Bother to Make It Easier? Why do we write programs? So the user can perform some task The more versatile the program, the more difficult it is to write. BUT it is more useable. The more complex the task, the more difficult it is to write. But that is often what a user needs. Always consider the user first. 27
Using a Sentinel Value We could let the user keep entering grades and when he s done enter some special value that signals us that he s done. This special signal value is called a sentinel value. We have to make sure that the value we choose as the sentinel isn t a legal value. For example, we can t use 0 as the sentinel in our example as it is a legal value for an exam score. The Priming Read When we use a sentinel value to control a while loop, we have to get the first value from the user before we encounter the loop so that it will be tested and the loop can be entered. This is known as a priming read. We have to give significant thought to the initialization of variables, the sentinel value, and getting into the loop. 28
New Pseudocode( ) <total> = 0 <grade_counter> = 1 Display Enter a grade: Priming read Read <grade> While ( <grade>!= SENTINEL ) <total> = <total> + <grade> <grade_counter> = <grade_counter> + 1 Display Enter another grade: Read <grade> End_while <average> = <total> / <grade_counter> Display Class average is:, <average> New C Code #include <stdio.h> #define SENTINEL -99 int main ( ) int counter, grade, total, average ; total = 0 ; counter = 1 ; printf( Enter a grade: ) ; scanf( %d, &grade) ; while (grade!= SENTINEL) total = total + grade ; counter = counter + 1 ; printf( Enter another grade: ) ; scanf( %d, &grade) ; average = total / counter ; printf ( Class average is: %d\n, average) ; return 0 ; 29
Final Clean C Code #include <stdio.h> #define SENTINEL -99 int main ( ) int counter ; /* counts number of grades entered */ int grade ; /* individual grade */ int total; /* total of all grades */ int average ; /* average grade */ /* Initializations */ total = 0 ; counter = 1 ; Final Clean C Code (con t) /* Get grades from user */ /* Compute grade total and number of grades */ printf( Enter a grade: ) ; scanf( %d, &grade) ; while (grade!= SENTINEL) total = total + grade ; counter = counter + 1 ; printf( Enter another grade (or %d to quit):, SENTINEL) ; scanf( %d, &grade) ; User friendly /* Compute and display the average grade */ average = total / counter ; printf ( Class average is: %d\n, average) ; return 0 ; 30
while loop: Example 2 gcd(i, j) = gcd(j, i%j) Start j!= 0? temp = i % j; i = j; j = temp; End while loop: gcd example #include<stdio.h> void main() int i, j, tmp; printf("\1: Please input two positive integer for finding their GCD:\n"); scanf("%d %d", &i, &j); while ( j!= 0 ) tmp = i % j; i = j; j = tmp; printf("\2: The GCD is %d \n",i); // 數? // 料 31
Using a while Loop to Check User Input #include <stdio.h> int main ( ) int number ; printf ( Enter a positive integer : ) ; scanf ( %d, &number) ; priming read while ( number <= 0 ) printf ( \nthat s incorrect. Try again.\n ) ; printf ( Enter a positive integer: ) ; scanf ( %d, &number) ; printf ( You entered: %d\n, number) ; return 0 ; The do-while Repetition Structure do statement(s) while ( condition ) ; The body of a do-while is ALWAYS executed at least once. 32
Check User Input Using do-while do printf ( Enter a positive number: ) ; scanf ( %d, &num) ; if ( num <= 0 ) printf ( \nthat is not positive. Try again\n ) ; while ( num <= 0 ) ; do printf ( Enter a letter from A through Z: ) ; scanf ( %c, &letter) ; while ( letter < A letter > Z ) ; Counter-Controlled loop: for loop * * condition-controlled loop 33
Counter-Controlled Repetition (Definite Repetition) If it is known in advance exactly how many times a loop will execute, it is known as a countercontrolled loop. int i = 1 ; while ( i <= 10 ) printf( i = %d\n, i) ; i = i + 1 ; Counter-Controlled Repetition (con t) Is the following loop a counter-controlled loop? while ( x!= y ) printf( x = %d, x) ; x = x + 2 ; 34
Event-Controlled Repetition (Indefinite Repetition) If it is NOT known in advance exactly how many times a loop will execute, it is known as an eventcontrolled loop or condition-controlled loop. sum = 0 ; printf( Enter an integer value: ) ; scanf( %d, &value) ; while ( value!= -1) sum = sum + value ; printf( Enter another value: ) ; scanf( %d, &value) ; Event-Controlled Repetition (con t) An event-controlled loop will terminate when some event occurs (which makes the condition true). The event may be the occurrence of a sentinel value, as in the previous example. There are other types of events that may occur, such as reaching the end of a data file. 35
The 3 Parts of a Loop #include <stdio.h> int main () int i = 1 ; initialization of loop control variable /* count from 1 to 100 */ while ( i < 101 ) test of loop termination condition printf ( %d, i) ; i = i + 1 ; modification of loop control variable return 0 ; The for Loop Repetition Structure The for loop handles details of the counter-controlled loop automatically. The initialization of the the loop control variable, the termination condition test, and control variable modification are handled in the for loop structure. for ( i = 1; i < 101; i = i + 1) initialization modification test 36
for for (for loop) for ( expr1 ; expr2 ; expr3 ) statements; next-statements; 數 行 數 --for (for loop) 流 for 流 expr1 expr2 false true statements expr3 next-statements 37
When Does a for-loop Initialize, Test and Modify? Just as with a while loop, a for loop initializes the loop control variable before beginning the first loop iteration, modifies the loop control variable at the very end of each iteration of the loop, and performs the loop termination test before each iteration of the loop. The for loop is easier to write and read for counter-controlled loops. Various forms of for loop counting for ( i = 0; i < 10; i = i + 1 ) printf ( %d\n, i) ; for ( i = 9; i >= 0; i = i - 1 ) printf ( %d\n, i) ; for ( i = 0; i < 10; i = i + 2 ) printf ( %d\n, i) ; for ( i = 9; i >= 0; i = i - 2 ) printf ( %d\n, i) ; 38
for loop--- 例 例 累 100 #include<stdio.h> k = 1 main() int i, sum=0; /* 數 i sum 數 */ for (i=1; i<=100; i=i+1) sum= sum+ i; printf( sum = %d \n, sum); /* sum */ k 流 for loop--- 例 數 累 流 說 理 / 數 N Sum=0 i=1 i<=n? true false 流 i=i+1 39
例 for loop--- 例 2 #include<stdio.h> main() int i,n, sum=0; printf( Please input an integer: ); scanf( %d, &N ); for (i=1; i<=n; i=i+1) sum= sum+ i; printf( 1+2+ +%d = %d \n,n, sum); /* 數 */ / 1+2+ +N*/ /* sum */ for loop--- 例 3 例 f(n)=n*(n-1)*(n-2)*(n-3) *3*2*1 -- 數 Factorial /* * Computes n! * Pre-condition: n is greater than or equal to zero */ Int factorial(int n) int i, /* local variables */ product; /* accumulator for product computation */ product = 1; /* Computes the product n x (n-1) x (n-2) x... x 2 x 1 */ for (i = n; i >= 1; --i) product = product * i; /* Returns function result */ return (product); --i; i = i -1; i 40
C --i, i--, ++i, i++ The increment operator ++ The decrement operator -- If we want to add one to a variable, we can say: count = count + 1; (count = count - 1;) Programs often contain statements that increment variables, so to save on typing, C provides these shortcuts: count++; (count--;) OR ++count; (--count;) Both do the same thing. They change the value of count by adding one to it. *But post or pre increment (decrement) have different implications. (come back later) Nested Loops Loops inside other loops! 41
Nested for loops-- 例 例 #include<stdio.h> main() int i, j, k; for (i=1; i<=9; i++) for (j=1; j<=9; j++) k = i*j; printf("%d*%d = %2d ", i, j, k); 行 : Nested for loop--- 例 1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 2*1= 2 2*2= 4 2*3 = 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 4*1= 4 4*2= 8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4* 8=32 4*9=36 5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54 7*1= 7 7*2=14 7*3=21 7 *4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6= 48 8*7=56 8*8=64 8*9=72 9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 若 列 42
Revised Nested for loops-- 例 例 #include<stdio.h> main() int i, j, k; for (i=1; i<=9; i++) for (j=1; j<=9; j++) k = i*j; printf("%d*%d = %2d ", i, j, k); printf( \n ); Nested for loops-- 例 for ( i = 1; i < 5; i = i + 1 ) for ( j = 1; j < 5; j = j + 1 ) if ( j % 2 == 0 ) printf ( O ) ; else printf ( X ) ; printf ( \n ) ; How many times is the if statement executed? What is the output? XOXO XOXO XOXO XOXO 43
Nested for loops-- 例 for ( i = 1; i < 7; i = i + 1 ) for ( j = i; j < 7; j = j + 1 ) if ( j % 2 == 0 ) printf ( O ) ; else printf ( X ) ; printf ( \n ) ; How many times is the if statement executed? What is the output? XOXOXO OXOXO XOXO OXO XO O Figure 5.14 Validating Input Using nested do-while statement 44
Nested for loop---lab 練 練 狀 列 列 // 8 rows # ### ##### ####### ######### ########### ############# ############### // 7 spaces // 2 spaces // 1 space // 0 space // 15 # Assignment 2 1. nested for loops 2. 1. 2. 年 (2005) 45