340 likes | 483 Views
CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. Week 5: Repetition Statements. Objectives: Understand the program control structure called loops Compare the different types of repetition structure. References: Chapter 4 (Lessons 4.7 – 4.11). Week 5: Outline (1/2).
E N D
CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/
Week 5: Repetition Statements Objectives: • Understand the program control structure called loops • Compare the different types of repetition structure • References: • Chapter 4 (Lessons 4.7 – 4.11) CS1010 (AY2011/2 Semester 1)
Week 5: Outline (1/2) • Introduction • while loops • Demo #1: Print integers • while loops: Examples • do-while loops • for loops • for loops: Odd integers • Exercise #1: Sum of multiples of 3 • Exercise #2: Asterisks CS1010 (AY2011/2 Semester 1)
Week 5: Outline (2/2) • Common errors • Some notes of caution • Exercise #3: Nested loops • Using ‘break’ in loop • Using ‘continue’ in loop • Exercise #4: Prime number CS1010 (AY2011/2 Semester 1)
0. Week 4 Ex4: NRIC Check Code (1/3) Algorithm for NRIC check code NRIC consists of 7 digits. Eg: 8730215 Step 1: Multiply the digits with corresponding weights 2,7,6,5,4,3,2 and add them up. Eg: 82 + 77 + 36 + 05 + 24 + 13 + 52 = 16+49+18+0+8+3+10 = 104 Step 2: Divide step 1 result by 11 to obtain the remainder. Eg: 104 % 11 = 5 CS1010 (AY2011/2 Semester 1) Week5 - 5
0. Week 4 Ex4: NRIC Check Code (2/3) Algorithm for NRIC check code (cont…) Step 3: Subtract step 2 result from 11 Eg: 11 – 5 = 6 Step 4: Match step 3 result in this table for the check code Eg: The check code corresponding to 6 is ‘F’. Therefore, the check code for 8730215 is ‘F’. CS1010 (AY2011/2 Semester 1) Week5 - 6
0. Week 4 Ex4: NRIC Check Code (3/3) Write a program Week4_NRIC.c to generate the check code given a 7-digit NRIC number. Your program should include a function generateCode that takes in a single integer (the NRIC number) and returns a character (which is the check code). You need to use the char type. (Explore this on your own.) A character constant is enclosed in single quotes (eg: 'A', 'Z'). The format specifier for char type is %c (to be used in a printf statement). This is your take-home exercise. CS1010 (AY2011/2 Semester 1) Week5 - 7
1. What are Loops? • Recall control structures: • Sequence (done!) • Selection: if, if-else, switch (done!) • Repetition • Loop: Allow us to specify the repetition of a groups of steps • When do you need to use loops? • Any steps repeated in the solution? If yes, which ones? • Do you know before-hand how many times to repeat the group of steps? If no, what is the condition to keep repeating? CS1010 (AY2011/2 Semester 1)
1. Flow Diagram CS1010 (AY2011/2 Semester 1)
2. while Loops while ( condition ) { // loop body } We call the number of times a loop repeats the number of iterations. If condition is true, execute loop body, otherwise terminate loop. CS1010 (AY2011/2 Semester 1)
3. Demo #1: Print Integers (1/2) • Write a program Week5_Integers.c to accept 2 integer a and b (assume ab) and print integers between a and b inclusive. • You should have a function print_integers(int,int) to do the printing of integers. • Sample run: Enter two integers a and b (a<=b): -3 8 -3 -2 -1 0 1 2 3 4 5 6 7 8 CS1010 (AY2011/2 Semester 1)
3. Demo #1: Print Integers (2/2) CS1010 (AY2011/2 Semester 1)
4. while Loops: Examples (1/3) • Example: Given a positive integer n, print positive odd integers up to n. void print_odd_integers(int n) { inti=1; while (i <= n) { printf("%d ", i); i += 2; } printf("\n"); } CS1010 (AY2011/2 Semester 1)
4. while Loops: Examples (2/3) • Trace the following codes manually and write out their outputs (assume a, b, c are integer variables). (a) a = 1; while (a*a < 1000) { printf("%d ", a); a *= 2; } printf("\n"); (b) b = 0; c = 99; while (b < c) { printf("b=%d, c=%d\n", b, c); b++; c--; } CS1010 (AY2011/2 Semester 1)
4. while Loops: Examples (3/3) • Trace the following code manually and write out its output (assume d is an integer variable). (c) d = 3; while (d = 1) { printf("d=%d\n", d); d = 99; } CS1010 (AY2011/2 Semester 1)
5. do-while Loops do { // loop body } while ( condition ); Execute loop body at least once. • Example: Print positive odd integers. // Pre-cond: n > 0 void print_odd_integers(int n) { inti=1; do { printf("%d ", i); i += 2; } while (i <= n); printf("\n"); } CS1010 (AY2011/2 Semester 1)
6. for Loops (1/2) for ( initialization; condition; update ) { // loop body } Initialization: initialize the loop variable Condition: repeat loop while the condition is true Update: change value of loop variable CS1010 (AY2011/2 Semester 1)
6. for Loops (2/2) • Example: Print numbers 1 to 10 int n; for (n=1; n<=10; n++) { printf("%3d", n); } • Steps: • n=1; • if (n<=10) {printf(…); n++;} • Go to step 2 CS1010 (AY2011/2 Semester 1)
7. for Loops: Odd Integers Version 4 Version 3 CS1010 (AY2011/2 Semester 1)
8. Exercise #1: Sum of Multiples of 3 • Modify the program Week5_OddIntegers_v3.c to read a positive integer n and then compute the sum of all integers between 1 and n which are multiples of 3 using a ‘for’ loop. Write a function called sum_multiples_of_3(int). • This problem can be solved with a formula, but we will use the ‘for’ loop just for exercise. • Call this program Week5_SumMultiples3.c • Sample run: Enter a positive integer: 50 Sum = 408 CS1010 (AY2011/2 Semester 1)
9. Exercise #2: Asterisks • Write a program Week5_Asterisks.c to read an integer n and print a certain number of asterisks on a single line. Write a function print_asterisks(int). • If n is non-positive, then no asterisk should be printed. • Sample runs: Think! What is the relationship between the number of * and the iteration number? Enter n: 3 ***** Done! Enter n: 6 *********** Done! Enter n: -2 Done! Enter n: 10 ******************* Done! CS1010 (AY2011/2 Semester 1)
10. Common Errors (1/2) • Off-by-one error; make sure the loop repeats exactly the correct number of iterations. • Make sure the loop body contains a statement that will eventually cause the loop to terminate. • Using ‘=’ where it should be ‘==’ (as in slide 15) • Putting ‘;’ where it should not be (just like for the ‘if’ statement) CS1010 (AY2011/2 Semester 1)
10. Common Errors (2/2) int main(void) { inti; for (i=0; i<10; i++); printf("%d\n", i); return 0; } • What are the outputs for the following programs? int main(void) { inti=0; while (i<10); { printf("%d\n", i); i++; } return 0; } CS1010 (AY2011/2 Semester 1)
11. Some Notes of Caution (1/2) • Involving real numbers double one_seventh = 1.0/7.0; double f = 0.0; while (f != 1.0) { printf("%f\n", f); f += one_seventh; } CS1010 (AY2011/2 Semester 1)
11. Some Notes of Caution (2/2) • Involving ‘wrap-around’ int a = 2147483646; inti; for (i=1; i<=5; i++) { printf("%d\n", a); a++; } CS1010 (AY2011/2 Semester 1)
12. Exercise #3: Nested Loops • Test out Week5_NestedLoopEx1.c, Week5_NestedLoopEx2.c andWeek5_NestedLoopEx3.c • Hand trace the programs and write out the outputs without running the programs • Verify your answers by running the programs CS1010 (AY2011/2 Semester 1)
13. Using ‘break’ in loop (1/2) • ‘break’ in switch statement; ‘break’ can also be used in a loop • Test out Week5_BreakInLoop.c CS1010 (AY2011/2 Semester 1)
13. Using ‘break’ in loop (2/2) • Use ‘break’ sparingly, because it violates the one-entry-one-exit control flow. • A loop with ‘break’ can be rewritten into one without ‘break’. // without ‘break’ int n, i, sum; intis_positive; // indicate if input n // is positive sum = 0; i= 1; is_positive = 1; while ((i<= 10) && is_positive) { scanf("%d", &n); if (n < 0) is_positive = 0; else { sum += n; i++; } } // with ‘break’ int n, i, sum; sum = 0; i = 1; while (i <= 10) { scanf("%d", &n); if (n < 0) break; sum += n; i++; } CS1010 (AY2011/2 Semester 1)
14. Using ‘continue’ in loop • Test out Week5_ContinueInLoop.c • ‘continue’ is even used less often than ‘break’ CS1010 (AY2011/2 Semester 1)
15. Exercise #4: Prime Number • Primality test is a classic programming problem • Given a positive integer, determine whether it is a prime • A prime number has two distinct factors (divisors): 1 and itself. Examples: 2, 3, 5, 7, 11, ... (Note: 1 is not a prime!) • Write a program Week5_PrimeTest.c. You should include a function is_prime(int). • Discuss this at the next lecture. • Sample runs: Enter a positive integer: 131 131 is a prime. Enter a positive integer: 713 713 is not a prime. CS1010 (AY2011/2 Semester 1)
Summary for Today (1/2) • Repetition statements (loops) • for, while, do-while • break and continue • Nested loops CS1010 (AY2011/2 Semester 1)
Summary for Today (2/2) • You have learned the 3 control structures: • Sequence, Selection, Repetition • With these, you are able to solve just any computing problem! • However, writing good programs is more than just learning the syntax: • Logic should be clear • Variables should be descriptive • Algorithm should be efficient CS1010 (AY2011/2 Semester 1)
Announcements/Things-to-do • Revise Chapter 4 (Lessons 4.7 – 4.11) • Deadline for Lab #2 • 10 September 2011, Saturday, 12 noon. • Practical Exam 1 (PE1) • Next Saturday 17 September 2011. • Please refer to module website, “CA” “PE” for more information. • To prepare for next week’s lecture: • Functions: Lessons 5.4 – 5.5 • Modular Programming CS1010 (AY2011/2 Semester 1)
End of File CS1010 (AY2011/2 Semester 1)