1 / 49

CS1010: Programming Methodology comp.nus.sg/~cs1010/

CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. 0. Revision (1/3). General form of if statements There can be any number of else-if fragments. The else fragment is optional but can only appear last.

hogan
Download Presentation

CS1010: Programming Methodology comp.nus.sg/~cs1010/

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. CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/

  2. 0. Revision(1/3) General form of if statements There can be any number of else-if fragments. The else fragment is optional but can only appear last. The curly brackets around a set of statements are required unless there is only one statement in the set. if (condition1 ) { statements; // To be executed if condition1 is true } elseif (condition2 ) { statements; // To be executed if condition2 is true // and all previous conditions are false } elseif (condition3 ) { statements; // To be executed if condition3 is true // and all previous conditions are false } … else { statements; // To be executed if and all previous // conditions are false } CS1010 (AY2013/4 Semester 1) Week5 - 2

  3. 0. Revision (2/3) A condition is an expression evaluated to true or false. Composed of expressions combined with relational operators and logical operators Relational Operators: <, <=, >, >=, ==, != Left associative Precedence: higher than && and || but lower than !. Logical Operators: &&, ||, ! Left associative Precedence (from high to low): !, &&, || Short-circuit evaluation: expr1 || expr2 : If expr1 is true, skip evaluating expr2 expr1 && expr2: If expr1 is false, skip evaluating expr2 Do not confuse with “=”! CS1010 (AY2013/4 Semester 1) Week5 - 3

  4. 0. Revision (3/3) General form of switch statements The value of expression must be an integer or a character “break” prevents statements in subsequent cases from being executed. switch(expression) { case value1: statements; // To be executed if expression == value1 break; case value2: statements; // To be executed if expression == value2 break; ... default: statements; // To be executed if expression does not // match any case values } CS1010 (AY2013/4 Semester 1) Week5 - 4

  5. Week 4 Ex3: NRIC Check Code (1/3) Algorithm for NRIC check code S/T + 7 digits +1 letter check code E.g.: S8730215F (valid), S8730216F(invalid, check code should be D) Step 1: Multiply the digits with corresponding weights 2,7,6,5,4,3,2 and add them up. E.g.: 82 + 77 + 36 + 05 + 24 + 13 + 52 = 16+49+18+0+8+3+10 = 104 Step 2: Divide step 1 result by 11 to obtain the remainder. E.g.: 104 % 11 = 5 CS1010 (AY2013/4 Semester 1) Week5 - 5

  6. Week 4 Ex3: NRIC Check Code (2/3) Algorithm for NRIC check code (cont…) Step 3: Subtract step 2 result from 11 E.g.: 11 – 5 = 6 Step 4: Match step 3 result in this table for the check code E.g.: The check code corresponding to 6 is ‘F’. Therefore, the check code for 8730215 is ‘F’. Sample run: Enter 7-digit NRIC number: 8730215 Check code is F CS1010 (AY2013/4 Semester 1) Week5 - 6

  7. Week 4 Ex3: 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 char generateCode(int) that takes in a single integer (the NRIC number) and returns a character (the check code). You need to use the char type. (Explore this on your own.) A character constant is enclosed in single quotes (e.g.: 'A', 'Z'). The format specifier for char type is %c (to be used in a printf() statement). Do not use techniques that are not covered in class, such as array. Your program may be long now but you can always improve it later. This is your take-home exercise. This exercise is available in CodeCrunch. CS1010 (AY2013/4 Semester 1) Week5 - 7

  8. Week 5: Repetition Statements Objectives: • Understand the program control structure called loops • Compare the different types of loops • References: • Chapter 4 Lessons 4.7 – 4.11 CS1010 (AY2013/4 Semester 1)

  9. Outline 0. Revision • Loops! • The while Loop • The do-while Loop • The for Loop • Exercise #1: Sum of Multiples of 3 • Exercise #2: Asterisks • Common Errors • Some Notes of Caution 9. Exercise #3: Tracing Nested Loops 10. Using break in Loop 11. Using continue in Loop 12. Exercise #4: Prime Number CS1010 (AY2013/4 Semester 1)

  10. Recall: Control Structures Sequence Selection if-else, switch Repetition Loops! CS1010 (AY2013/4 Semester 1) Week5 - 10

  11. 1. LOOPS! (1/2) “A program without a loop and a structure variable isn’t worth writing.” Alan J.Perlis Yale University The first recipient of ACM Turing Award • A loop is a statement whose job is to repeatedly execute some other statement(s). CS1010 (AY2013/4 Semester 1) Week5 - 11

  12. 1. LOOPS! (2/2) Each round of the loop is called an iteration. Loop condition loop body false cond? true Some statement(s) CS1010 (AY2013/4 Semester 1) Week5 - 12

  13. 1. Loop: Demo (1/3) • Keep prompting the user to input a non-negative integer, and output that integer. • Halt when the input is negative. Enter a number: 12 You entered: 12 Enter a number: 0 You entered: 0 Enter a number: 26 You entered: 26 Enter a number: 5 You entered: 5 Enter a number: -1 • Key observations: • You keep repeating a task while certain condition is (not) met • You do not know beforehand how many iterations there will be. CS1010 (AY2013/4 Semester 1) Week5 - 13

  14. 1. Loop: Demo (2/3) intmain(void) { intnum; printf("Enter a number: "); scanf("%d", &num); if (num >= 0) { printf("You entered: %d\n", num); printf("Enter a number: "); scanf("%d", &num); } else return0; if (num >= 0) { printf("You entered: %d\n", num); printf("Enter a number: "); scanf("%d", &num); } else return0; .... } Enter a number: 12 You entered: 12 Enter a number: 0 You entered: 0 Enter a number: 26 You entered: 26 Enter a number: 5 You entered: 5 Enter a number: -1 Loop condition Loop body CS1010 (AY2013/4 Semester 1) Week5 - 14

  15. 1. Loop: Demo (3/3) Week5_Read_print.c intmain(void) { int num; printf("Enter a number: "); scanf("%d", &num); while (num >= 0) { printf("You entered: %d\n", num); printf("Enter a number: "); scanf("%d", &num); } return 0; } Loop condition false num >= 0? true Loop body printf … printf … scanf… CS1010 (AY2013/4 Semester 1) Week5 - 15

  16. 2. The whileLoop while ( condition ) { // loop body } If condition is true, execute loop body; otherwise, terminate loop. false cond? true Loop body CS1010 (AY2013/4 Semester 1)

  17. 2.1 The whileLoop: Demo (1/2) Enter a number: 12 Enter a number:0 Enter a number: 26 Enter a number: 5 Enter a number: -1 The maximum number is 26 • Keep prompting the user to input a non-negative integer • Halt when the input is negative. • Output the maximum number so far maxi = 0; num  input; while (num >= 0) { if (maxi < num) maxi = num; num  input; } print maxi; CS1010 (AY2013/4 Semester 1) Week5 - 17

  18. 2.1 The whileLoop: Demo (2/2) Week5_Find_max.c intmain(void) { int num, maxi = 0; printf("Enter a number: "); scanf("%d", &num); while (num >= 0) { if (maxi < num) { maxi = num; } printf("Enter a number: "); scanf("%d", &num); } prinf("The maximum number is %d\n", maxi); return 0; } CS1010 (AY2013/4 Semester 1) Week5 - 18

  19. 2.2 whileLoop Condition (1/2) When the loop condition is false at the beginning, the loop body is not executed. Output: ? int a =2; int b =7; while (a == b) { printf(“%d\n”, a); a = a + 2; } false cond? true Loop body CS1010 (AY2013/4 Semester 1) Week5 - 19 

  20. 2.2 whileLoop Condition (2/2) When the loop condition is always true, the loop body is executed forever – infinite loop. Output: ? int a =2; int b =7; while (a != b) { printf(“%d\n”, a); a = a + 2; } false cond? true Loop body CS1010 (AY2013/4 Semester 1) Week5 - 20 

  21. 2.3 Tracing whileLoop (1/3) • Trace the following codes manually and write out their outputs (assume all variables are of type int) (a) a = 1; while (a*a < 100) { printf("%d ", a); a *= 2; } printf("\n"); (b) b = 0; c = 9; while (b < c) { printf("b=%d,c=%d\n", b, c); b++; c--; } printf("outside: b=%d,c=%d\n", b, c); CS1010 (AY2013/4 Semester 1) 

  22. 2.3 Tracing whileLoop (2/3) • Example: Given a positive integer n, print out its digits from least significant to most significant. • Sample run: Enter a positive integer: 28943 3 4 9 8 2 CS1010 (AY2013/4 Semester 1)

  23. 2.3 Tracing whileLoop (3/3) Week5_Print_digits.c // Precond: n > 0 void print_digits(intn) { int digit; while (n > 0) { digit = n%10; printf("%d\n", digit); n /= 10; } } For the number 28943, what are the values of n and digit before the loop and after each iteration? CS1010 (AY2013/4 Semester 1) 

  24. 3. The do-whileLoop (1/2) do { // loop body } while ( condition ); Execute loop body at least once. Loop body cond? true false CS1010 (AY2013/4 Semester 1)

  25. 3. The do-whileLoop (2/2) do { // loop body } while ( condition ); Week5_Count_digits.c // Precond: n > 0 intcount_digits(intn) { int counter = 0; do { counter++; n /= 10; } while (n > 0); return counter; } • Example: Count the number of digits in an integer. What happens when n is 0? CS1010 (AY2013/4 Semester 1)

  26. 4. The for Loop for ( initialization; condition; update ) { // loop body } Update: change value oftheloop variable Initialization: initialize the loop variable Condition: repeat loop while the condition is true Initialization int n; for (n=1; n<=10; n++) { printf("%d\n", n); } true Loop body cond? false Loop variable: a variable which is involved in the loop condition. Update CS1010 (AY2013/4 Semester 1)

  27. Week5_OddIntegers_v1.c #include <stdio.h> void print_odd_integers(int); intmain(void) { int num; printf("Enter a positive integer: "); scanf("%d", &num); print_odd_integers(num); return0; } // Precond: n > 0 void print_odd_integers(intn) { inti; for (i=1; i<=n; i+=2) printf("%d ", i); printf("\n"); } 4.1 The for Loop: Odd Integers (1/2) Initialization: i = 1 Condition: i <= n Body:printf(…) Update: i+=2 CS1010 (AY2013/4 Semester 1) 

  28. Week5_OddIntegers_v2.c Week5_OddIntegers_v3.c // Precond: n > 0 void print_odd_integers(intn) { inti; for (i=1; i<=n; i++) if (i%2 != 0) printf("%d ", i); printf("\n"); } // Precond: n > 0 void print_odd_integers(intn) { for ( ; n > 0; n--) if (n%2 != 0) printf("%d ", n); printf("\n"); } 4.1 The for Loop: Odd Integers (2/2) First version inti; for (i=1; i<=n; i+=2) printf("%d ", i); printf("\n"); Values printed from largest to smallest. Empty statement CS1010 (AY2013/4 Semester 1)

  29. Outline 0. Revision • Loops! • The while Loop • The do-while Loop • The for Loop • Exercise #1: Sum of Multiples of 3 • Exercise #2: Asterisks • Common Errors • Some Notes of Caution 9. Exercise #3: Tracing Nested Loops 10. Using break in Loop 11. Using continue in Loop 12. Exercise #4: Prime Number CS1010 (AY2013/4 Semester 1)

  30. 5. Exercise #1: Sum of Multiples of 3 (1/2) • Modify the program Week5_OddIntegers_v1.c to read a positive integer n and then compute the sum of all integers which are multiples of 3 between 1 and n 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 loops just for exercise. • Call this program Week5_SumMultiples3.c • Sample run: Enter a positive integer: 50 Sum = 408 CS1010 (AY2013/4 Semester 1)

  31. 5. Exercise #1: Sum of Multiples of 3 (2/2) precondition: n > 0 sum  0 i n while i > 0 if i is multiple of 3 then sum  sum + i i  i - 1 return sum • Pseudo-code using a while loop: CS1010 (AY2013/4 Semester 1)

  32. 6. Exercise #2: Asterisks (1/2) • 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 n and the number of *? Enter n: 3 ***** Done! Enter n: 6 *********** Done! Enter n: 10 ******************* Done! Enter n: -2 Done! CS1010 (AY2013/4 Semester 1)

  33. 6. Exercise #2: Asterisks (2/2) • 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). Pseudo-code: read input n ; if n is non-positive print “done” and end program ; m compute the number of asterisks given n print_asterisks(m) end program; CS1010 (AY2013/4 Semester 1)

  34. 7. Common Errors (1/2) Week5_CommonErrors1.c • What are the outputs for the following programs? (Do not code and run them. Trace the programs manually.) inti; for (i=0; i<10; i++); printf("%d\n", i); Week5_CommonErrors2.c inti = 0; while (i<10); { printf("%d\n", i); i++; } • Putting ‘;’ where it should not be CS1010 (AY2013/4 Semester 1) 

  35. 7. Common Errors (2/2) Week5_CommonErrors3.c intz = 3; while (z = 1) { printf("z = %d\n", z); z = 99; } • Using ‘=’ where it should be ‘==’ • Missing a statement that eventually causes the loop to terminate • Off-by-one error: The loop stops one iteration too early or too late. CS1010 (AY2013/4 Semester 1) 

  36. 8. Some Notes of Caution (1/2) • Involving real numbers • Trace the program manually without running it. double one_seventh = 1.0/7.0; double f = 0.0; while (f != 1.0) { printf("%f\n", f); f += one_seventh; } Week5_Caution1.c CS1010 (AY2013/4 Semester 1) 

  37. 8. Some Notes of Caution (2/2) • Involving ‘wrap-around’ • Trace the program manually without running it. inta = 2147483646; inti; for (i=1; i<=5; i++) { printf("%d\n", a); a++; } Week5_Caution2.c CS1010 (AY2013/4 Semester 1) 

  38. Outline 0. Revision • Loops! • The while Loop • The do-while Loop • The for Loop • Exercise #1: Sum of Multiples of 3 • Exercise #2: Asterisks • Common Errors • Some Notes of Caution 9. Exercise #3: Tracing Nested Loops 10. Using break in Loop 11. Using continue in Loop 12. Exercise #4: Prime Number CS1010 (AY2013/4 Semester 1)

  39. 9. Exercise #3: Tracing Nested Loops • You are given Week5_NestedLoop1.c, Week5_NestedLoop2.c and Week5_NestedLoop3.c • Hand trace the programs and write out the outputs without running the programs • Verify your answers by running the programs CS1010 (AY2013/4 Semester 1)

  40. 9. Exercise #3: Tracing Nested Loops Week5_NestedLoop1.c int a, b; a = 1; while (a <= 4) { b = a + 3; while (b <= 10) { printf ("a = %d, b = %d\n", a, b); b += 3; } a++; } … CS1010 (AY2013/4 Semester 1) 

  41. 10. Using break in Loop (1/2) • Exit the immediate loop • Can be used in switch statement and loops 1 1 Ya 1 2 2 1 Ya 2 2 3 1 Ya 3 2 • for (i=1; i<=3; i++){ • printf ("%d\n", i); • printf ("Ya\n"); • } 1 Ya 2 Ya 3 Ya for (i=1; i<=3; i++) { for (j=1; j<=3; j++) { printf ("%d,%d\n", i, j); if (j==2) break; printf ("Ya\n"); } } for (i=1; i<=3; i++){ printf ("%d\n", i); if (i==2) break; printf ("Ya\n"); } 1 Ya 2 CS1010 (AY2013/4 Semester 1)

  42. 10. 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 intn, i = 1, sum = 0; intisValid = 1; while ((i <= 5) && isValid){ scanf("%d", &n); if (n < 0) isValid = 0; else { sum += n; i++; } } // with break intn, i = 1, sum = 0; while (i <= 5) { scanf("%d", &n); if (n < 0) break; sum += n; i++; } CS1010 (AY2013/4 Semester 1)

  43. 11. Using continue in Loop • Skip the rest of the current iteration • Can be used in loops but even less often than ‘break’ 1 1 Ya 1 2 1 3 Ya 2 1 Ya 2 2 2 3 Ya 3 1 Ya 3 2 3 3 Ya • for (i=1; i<=3; i++){ • printf ("%d\n", i); • printf ("Ya\n"); • } 1 Ya 2 Ya 3 Ya for (i=1; i<=3; i++) { for (j=1; j<=3; j++) { printf ("%d,%d\n", i, j); if (j==2) continue; printf ("Ya\n"); } } for (i=1; i<=3; i++){ printf ("%d\n", i); if (i==2) continue; printf ("Ya\n"); } 1 Ya 2 3 Ya CS1010 (AY2013/4 Semester 1)

  44. 12. Exercise #4: Prime Number (1/2) • 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). (What does it return?) • Sample runs: Enter a positive integer: 131 131 is a prime. Enter a positive integer: 713 713 is not a prime. CS1010 (AY2013/4 Semester 1)

  45. 12. Exercise #4: Prime Number (2/2) • This is your take-home exercise. • This exercise is mounted on CodeCrunch. • We will discuss this in the next lecture. CS1010 (AY2013/4 Semester 1)

  46. Summary for Today (1/2) • Repetition statements (loops) • for, while, do-while • Nested loops • breakand continue CS1010 (AY2013/4 Semester 1)

  47. 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: • Design • Logic should be clear • Algorithm should be efficient • Style • Names of variables/functions should be descriptive • Programs should be indented and commented appropriately CS1010 (AY2013/4 Semester 1)

  48. Announcements/Things-to-do • Revise Chapter 4 (Lessons 4.7 – 4.11) • Lab 2 • This Saturday, 14 Sep, 9am • PE1 • Up to and including repetition statements • Next Saturday, 21 Sep • To prepare for next week’s lecture: • Read Chapter 5 Functions CS1010 (AY2013/4 Semester 1)

  49. End of File

More Related