Sie sind auf Seite 1von 47

# 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

Week5 - 2

## Week 5: Outline (1/2)

1. Week 4 Exercise #3: NRIC Check Code 2. Loops! 3. The while Loop
3.1 Demo 3.2 Loop condition 3.3 Tracing

5.1 Odd Integers

Week5 - 3

## Week 5: Outline (2/2)

8. Common Errors
9. Some Notes of Caution 10. Exercise #3: Tracing Nested Loops

## 11. Using break in Loop

12. Using continue in Loop 13. Exercise #4: Prime Number (take-home)

Week5 - 4

## 1. Week 4 Ex3: 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

Week5 - 5

## 1. Week 4 Ex3: 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
1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I 10 11 Z J

## Therefore, the check code for 8730215 is F.

Sample run:
CS1010 (AY2013/4 Semester 1)

Week5 - 6

## 1. 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 (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). Do not use techniques that are not covered in class, such as array. Your program may be long now. You can write an improved version later. This is your take-home exercise. This exercise is mounted on CodeCrunch.
Week5 - 7

if-else, switch

## CS1010 (AY2013/4 Semester 1)

Week5 - 8

2. LOOPS! (1/2)
A program without a loop and a structure variable isnt worth writing.
Alan J.Perlis Yale University The first recipient of ACM Turing Award

Week5 - 9

2. LOOPS! (2/2)
Loop condition
cond?
true

## Each round of the loop is called an iteration.

false

loop body

Some statement(s)

Week5 - 10

## 2. Loop: Demo (1/3)

Keep prompting the user to input a non-negative integer, and output that integer. Halt the loop when the input is negative.

Key observations:

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

You keep repeating a task while certain condition is met, or alternatively, you repeat until the condition is not met. You do not know beforehand how many iterations there will be.
Week5 - 11

## 2. Loop: Demo (2/3)

Same code repeated
Algorithm: condition read num if (num >= 0) { print the value entered read num } body else end input request

if (num >= 0) { print the value entered read num } else end input request ....

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

Week5 - 12

## 2. Loop: Demo (3/3)

Week5_Read_print.c int main(void) int num; num >= 0? true printf printf scanf {

false

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

Week5 - 13

## 3. The while Loop

while ( condition ) { // loop body }
cond? true Loop body false

Week5 - 14

## 3.1 The while Loop: Demo (1/3)

Keep prompting the user to enter a nonnegative integer. Halt the loop when the input is negative, and output the maximum integer entered so far.

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

Week5 - 15

## 3.1 The while Loop: Demo (2/3)

maxi = 0; read num; if (num >= 0) { if (maxi < num) maxi = num; read num; } else stop; if (num >= 0) { if (maxi < num) maxi = num; read num; } else stop; ... print maxi;
CS1010 (AY2013/4 Semester 1) Week5 - 16

maxi = 0; read num; while (num >= 0) { if (maxi < num) maxi = num; read num; } print maxi;

## 3.1 The while Loop: Demo (3/3)

int main(void) { int num, maxi = 0; Week5_Find_max.c

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 - 17

## 3.2 while Loop Condition (1/2)

a = 2;
b = 7; while (a == b) { print a;

Output: ?

a = a + 2;
}

is not executed.

Week5 - 18

## 3.2 while Loop Condition (2/2)

a = 2;
b = 7; while (a != b) { print a;

Output: ?

a = a + 2;
}

Week5 - 19

## 3.3 Tracing while Loop (1/4)

(a)

Trace the following codes manually and write out their outputs (assume all variables are of type int)
a = 1; while (a*a < 100) { printf("%d ", a); a *= 2; } printf("\n"); 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);
Week5 - 20

(b)

## 3.3 Tracing while Loop (2/4)

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) Week5 - 21

## 3.3 Tracing while Loop (3/4)

Example: Given a positive integer n, print out its digits from least significant to most significant.
// Precond: n > 0 void print_digits(int n) int digit;
Week5_Print_digits.c

## while (n > 0) { digit = n%10; printf("%d\n", digit); n /= 10; } }

CS1010 (AY2013/4 Semester 1) Week5 - 22

## 3.3 Tracing while Loop (4/4)

// Precond: n > 0 void print_digits(int n) int digit;
Week5_Print_digits.c

while (n > 0) { digit = n%10; printf("%d\n", digit); n /= 10; } } n initially n @ point digit @ point

## CS1010 (AY2013/4 Semester 1)

What are the values of n and digit after exiting the loop?

Week5 - 23

## 4. The do-while Loop (1/2)

do { // loop body } while ( condition );
Loop body

true

cond?

false

Week5 - 24

## 4. The do-while Loop (2/2)

Example: Count the number of digits in an integer.
// Precond: n > 0 int count_digits(int n) int counter = 0; do { counter++; n /= 10; } while (n > 0); return counter; }
CS1010 (AY2013/4 Semester 1) Week5 - 25

## do { // loop body } while ( condition );

Week5_Count_digits.c

## 5. The for Loop (1/2)

for ( initialization; condition; update ) { // loop body }
Initialization: initialize the Condition: repeat loop loop variable while the condition on loop variable is true Update: change value of loop variable
CS1010 (AY2013/4 Semester 1) Week5 - 26

## 5. The for Loop (2/2)

Example: Print numbers 1 to 10
int n; for (n=1; n<=10; n++) { printf("%3d", n); }
Steps:

3. Exit the loop

Week5 - 27

## 5.1 The for Loop: Odd Integers (1/2)

Week5_OddIntegers_v1.c #include <stdio.h> void print_odd_integers(int); int main(void) { int num; printf("Enter a positive integer: "); scanf("%d", &num); print_odd_integers(num); return 0; }

// Precond: n > 0 void print_odd_integers(int n) int i; for (i=1; i<=n; i+=2) printf("%d ", i); printf("\n"); }
CS1010 (AY2013/4 Semester 1)

Week5 - 28

## 5.1 The for Loop: Odd Integers (2/2)

Week5_OddIntegers_v2.c // Precond: n > 0 void print_odd_integers(int n) { int i; for (i=1; i<=n; i++) if (i%2 != 0) printf("%d ", i); printf("\n"); } Week5_OddIntegers_v3.c // Precond: n > 0 void print_odd_integers(int n) { for ( ; n > 0; n--) if (n%2 != 0) Values printed from printf("%d ", n); Empty largest to smallest. printf("\n"); statement }

Week5 - 29

## 6. 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 the for loop just for exercise.

Call this program Week5_SumMultiples3.c Sample run: Enter a positive integer: 50 Sum = 408

Week5 - 30

## 6. Exercise #1: Sum of Multiples of 3 (2/2)

How about using a while loop instead? Pseudo-code using a while loop: 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

Week5 - 31

## 7. 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 Enter n: 3 ***** Done! Enter n: 6 *********** Done!
the relationship between n and the number of *?

## Enter n: 10 ******************* Done!

CS1010 (AY2013/4 Semester 1)

Enter n: -2 Done!

Week5 - 32

## 7. 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) Week5 - 33

## 8. Common Errors (1/2)

What are the outputs for the following programs? (Do not code and run them. Trace the programs manually.)
int i; for (i=0; i<10; i++); printf("%d\n", i);
Week5_CommonErrors1.c

## 8. Common Errors (2/2)

int z = 3; while (z = 1) { printf("z = %d\n", z); z = 99; }
Week5_CommonErrors3.c

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 == Putting ; where it should not be (just like for the if statement)
Week5 - 35

## 9. 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

Week5 - 36

## 9. Some Notes of Caution (2/2)

Involving wrap-around
Trace the program manually without running it. int a = 2147483646; int i; for (i=1; i<=5; i++) { printf("%d\n", a); a++; }
Week5_Caution2.c

Week5 - 37

## 10. 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

Week5 - 38

## 11. Using break in Loop (1/2)

You have seen break in switch statement break can also be used in a loop Test out Week5_BreakInLoop.c

Week5 - 39

## 11. Using break in Loop (2/2)

Use break sparingly, because it violates the one-entryone-exit control flow. A loop with break can be rewritten into one without break.
// without break int n, i = 1, sum = 0; int isValid = 1; while ((i <= 5) && isValid){ scanf("%d", &n); if (n < 0) isValid = 0; else { sum += n; i++; } }
Week5 - 40

// with break int n, i = 1, sum = 0; while (i <= 5) { scanf("%d", &n); if (n < 0) break; sum += n; i++; }
CS1010 (AY2013/4 Semester 1)

## 12. Using continue in Loop

Test out Week5_ContinueInLoop.c

Week5 - 41

## 13. 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.

Week5 - 42

## 13. 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.

Week5 - 43

## for, while, do-while

Nested loops break and continue

Week5 - 44

## 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:

## CS1010 (AY2013/4 Semester 1)

Week5 - 45

Announcements/Things-to-do

## 21st September 2013, Saturday See web page for details:

http://www.comp.nus.edu.sg/~cs1010/3_ca/pe.html