Download Presentation  The PPT/PDF document "CS1010: Programming Methodology" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, noncommercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/
Slide2Week 5: Repetition Statements
Objectives:
Understand the program control structure called loops
Compare the different types of repetition structure
CS1010 (AY2012/3 Semester 1)
Week5  2
References:
Chapter 4
Lessons
4.7 –
4.11
Slide3Week 5: Outline (1/2)
Week 4 Exercise #3: NRIC Check Code
Loops!
The
while
Loop
3.1 Demo
3.2 Loop condition
3.3 TracingThe dowhile LoopThe for Loop5.1 Odd IntegersExercise #1: Sum of Multiples of 3Exercise #2: Asterisks
CS1010 (AY2012/3 Semester 1)
Week5 
3
Slide4Week 5: Outline (2/2)
Common Errors
Some Notes of Caution
Exercise #3: Tracing Nested Loops
Using
break
in Loop
Using
continue in LoopExercise #4: Prime Number (takehome)CS1010 (AY2012/3 Semester 1)Week5  4
Slide51. Week 4 Exercise #2: Taxi Fare (1/3)
The taxi fare structure in Singapore must be one of the most complex in the world! See
http://www.taxisingapore.com/taxifare/
Write a program
Week4_TaxiFare.c that reads the following input data (all are of int type) from the user, and computes the taxi fare:
dayType: 0 represents weekends and public holidays (PH for short); 1 represents weekdays and nonPH
boardHour
,
boardMin: the hour and minute the passengers board the taxi (eg: 14 27 if the passengers board the taxi at 2:27 PM)distance: the distance of the journey, in metresYour program should have a function float computeFare(int dayType, int
boardTime
,
int
distance)
The parameter
boardTime
is converted from the input data boardHour and boardMin. It is the number of minutes since 0:00hr.Eg: If boardHour and boardMin are 14 and 27 respectively, then boardTime is 867.
Week4  5
CS1010 (
AY2012/3
Semester 1)
Slide61. Week 4 Exercise
#2: Taxi Fare (2/3)
To implement the actual taxi fare could be a PE question
. In this exercise, we use a (grossly) simplified fare structure:
Basic Fare:
Surcharge
(applicable at the time of boarding):
Week4 
6CS1010 (AY2012/3 Semester 1)Flagdown (inclusive of 1st km or less)$3.40Every 400m thereafter or less up to 10.2km
$0.22
Every 350m thereafter or less after 10.2km
$0.22
dayType
Midnight charge (12am – 5:59am)
Peak hour charge (6am – 9:29am)
Peak
hour charge (6pm – 11:59pm)0: Weekends & PH50% of metered fareNone25% of metered fare1: Weekdays and nonPH
50% of metered fare25% of metered fare25% of metered fare
Slide71. Week 4 Exercise #2: Taxi Fare (3/3)
You are given an incomplete program
Week4_TaxiFarePartial.c
. Complete the program. This exercise is mounted on
CodeCrunch.Sample runs below for your checking
Week4 
7
CS1010 (
AY2012/3 Semester 1)Day type: 0Boarding hour and minute: 14 27Distance: 10950
Total taxi fare is
$9.12
First 1km: $3.40
Next 9.2km: 23
$0.22 = $5.06
Next 750m: 3
$0.22 = $0.66Basic fare = $9.12No surchargeTotal fare = $9.12Day type: 1
Boarding hour and minute: 9 20
Distance:
6123
Total taxi fare is
$7.83
First 1km: $3.40
Next 5123m: 13
$0.22 = $2.86
Basic fare = $6.26
Surcharge = 25% $6.26 = $1.57
Total fare = $7.83
Day type:
1
Boarding hour and minute:
5 59
Distance: 9000Total taxi fare is $11.70
First 1km: $3.40
Next 8km: 20
$0.22 = $4.40
Basic fare = $7.80
Surcharge = 50% $7.80 = $3.90
Total fare = $11.70
Slide81. Week 4 Exercise #2: Taxi Fare
Week4 
8
CS1010 (
AY2012/3 Semester 1)
float
computeFare
(
int daytype, int bTime, int
dist
)
{
basicFare
=
calcBasicFare(dist) ; return includeSurcharge
(basicFare,
daytype
,
bTime
) ;
}
float
calcBasicFare
(
int
dist
){
// Pre
cond
: 0 <= dist ; if (dist
<= 1000)
return 3.40;
else
if
(
dist
<= 10200
&&
dist
> 1000
)
return (3.40
+
ceil((
dist
 1000) /
400.0) * INCREMENT);
else
if
(
dist
> 10200)
return (3.40
+
9200 / 400.0 * INCREMENT +
(ceil((
dist

10200)
/
350.0))
*
INCREMENT);
}
Slide91. Week 4 Exercise #2: Taxi Fare
Week4 
9
CS1010 (
AY2012/3 Semester 1)
float
computeFare
(
int daytype, int bTime, int
dist
)
{
basicFare
=
calcBasicFare(dist) ; return includeSurcharge
(basicFare,
daytype
,
bTime
) ;
}
float
includeSurcharge
(float fare,
int
dType
,
int
bTime
){ // Precond: dType
= 0 or 1, 0 <=
bTime
<= 2359 ;
if (
bTime
< 360
&& (
dType
== 0 
dType
== 1
)
)
return fare * 1.50;
else
if
(
dType
== 1 && (
bTime
< 600
&&
dtime
>=360
))
return fare * 1.25;
else if (
b
Time
>= 1080)
return fare * 1.25;
else return fare ;
}
Slide101. 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
+
2
4
+
1
3 + 52 = 16+49+18+0+8+3+10 = 104Step 2: Divide step 1 result by 11 to obtain the remainder.Eg: 104 % 11 = 5
Week5  10
Week5 
10
CS1010 (AY2012/3 Semester 1)
Slide111. 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
Eg: The check code corresponding to 6 is ‘F’.
Therefore, the check code for
8730215
is ‘F’.Sample run:1
2
3
4
5
6
7
8
9
10
11
A
B
C
D
E
F
G
H
I
Z
J
Week5 
11
Week5 
11
Enter 7digit NRIC number:
8730215
Check code is
F
CS1010 (AY2012/3 Semester 1)
Slide121. Week 4 Ex3: NRIC Check Code (3/3)
Write a program
Week4_NRIC.c
to generate the check code given a 7digit 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 takehome exercise.This exercise is mounted on CodeCrunch.
Week5 
12
Week5 
12
CS1010 (AY2012/3 Semester 1)
Slide131. Week 4 Ex3: NRIC Check code
Step 1
: Multiply the digits with corresponding weights
2,
7,6,
5,4,3
,
2
and add them up.Eg: 82 + 77 + 36 + 05 +
2
4
+
1
3
+
52 = 16+49+18+0+8+3+10 = 104 // Extract the digits digit7 = num%10; num
/= 10; digit6 = num%10;
num
/= 10;
digit5 = num%10;
num
/= 10;
digit4 = num%10;
num
/= 10;
digit3 = num%10;
num
/= 10;
digit2 = num%10;
num
/= 10;
digit1 = num%10;
step1 = digit1*2 + digit2*7 + digit3*6 + digit4*5 + digit5*4 + digit6*3 + digit7*2
;
Week5 
13
Week5 
13
Slide141. Week 4 Ex3: NRIC Check code
Step
2: Divide step 1 result by 11 to obtain the remainder.
Eg
: 104 % 11 = 5
step2 = step1 % 11;
Step 3: Subtract step 2 result from 11
Eg
: 11 – 5 = 6step3 = 11  step2;Week5  14Week5  14CS1010 (AY2012/3 Semester 1)
Slide151. Week 4 Ex3: NRIC Check Code
Step
4: Match step 3 result in this table for the check code
switch
(step3) {
case 1: code = 'A'; break;
case 2: code = 'B'; break;
case 3: code = 'C'; break;
case 4: code = 'D'; break; case 5: code = 'E'; break; case 6: code = 'F'; break; case 7: code = 'G'; break; case 8: code = 'H'; break;
case 9: code = 'I'; break;
case 10: code = 'Z'; break;
case 11: code = 'J';
} // end
switch
1
2
3
4
5
6
7
8
9
10
11
A
B
C
D
E
F
G
H
I
Z
J
Week5 
15
Week5 
15
CS1010 (AY2012/3 Semester 1)
Slide16Recall: Control Structures
Week5 
16
Week5  16
Sequence
Selection
Repetition
ifelse, switch
CS1010 (AY2012/3 Semester 1)
Slide172. LOOPS! (1/2)
Week5 
17
Week5  17
“A program without a loop and a structure variable isn’t worth writing.”
Alan
J.Perlis
Yale University
The first recipient of ACM Turing AwardA loop is a statement
whose job is to
repeatedly
execute some other statement(s).
CS1010 (AY2012/3 Semester 1)
Slide182. LOOPS! (2/2)
Week5 
18
cond
?
Some
statement(s)
true
false
loop body
Loop condition
Week5 
18
Each round of the loop is called an
iteration
.
CS1010 (AY2012/3 Semester 1)
Slide192. Loop: Demo (1/3)
Keep prompting the user to input a nonnegative integer, and output that integer.
Halt the loop when the input is negative.
Enter a number:
12
You entered: 12
Enter a number:
0
You entered: 0Enter a number: 26You entered: 26Enter a number: 5You entered: 5Enter a number: 1Week5  19Week5  19
Key observations:
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.
CS1010 (AY2012/3 Semester 1)
Slide202. Loop: Demo (2/3)
int
main(void) {
int
num;
printf
("Enter a number: "); scanf("%d", &num); if (num < 0) return 0; printf("You entered: %d\n", num); printf("Enter a number: ");
scanf("%d", &num
);
if
(num < 0) return
0;
printf("You entered: %d\n", num); printf("Enter a number: ");
scanf("%d", &num);
....
}
Week5 
20
Week5 
20
Loop condition
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 body
CS1010 (AY2012/3 Semester 1)
Slide212. Loop: Demo (3/3)
Week5 
21
num
>= 0?
printf
…
printf
… scanf …truefalse
Week5 
21
CS1010 (AY2012/3 Semester 1)
int
main(
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;}Week5_Read_print.c
Slide223. The while
Loop
CS1010 (AY2012/3 Semester 1)
Week5  22
while (
condition
)
{ // loop body}cond?
Loop body
true
false
If condition is
true
, execute
loop body; otherwise, terminate loop.
Slide233.1 The while
Loop: Demo (1/3)
Enter a number:
12Enter a number:
0Enter a number:
26
Enter
a number: 5Enter a number: 1The maximum number is 26Week5  23Week5  23CS1010 (AY2012/3 Semester 1)
Keep prompting the user to input a nonnegative integer, and output that integer.
Halt the loop when the input is negative,
and output the maximum integer input so far.
Slide24
3.1 The while
Loop: Demo (2/3)
Week5  24
maxi = 0;
num
input;
while (num >= 0) { if (maxi < num) maxi = num; num
input;
}
print maxi;
maxi = 0;
num
input; if (
num < 0) {
print maxi; stop;
}
if (maxi < num)
maxi = num ;
num
input;
if (
num
< 0) {
print maxi; stop;
}
if (maxi < num)
maxi = num;num input;...Week5  24
CS1010 (AY2012/3 Semester 1)
Slide253.1 The while
Loop: Demo (3/3)
Week5  25
Week5 
25
CS1010 (AY2012/3 Semester 1)
int
main(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
;
}
Week5_Find_max.c
Slide263.2 while
Loop
Condition (1/2)
When the loop condition is always false
, the loop body is not executed.
Week5 
26
Output:
?
Week5 
26
CS1010 (AY2012/3 Semester 1)
a = 2;
b = 7;
while (a == b) {
print a;
a = a + 2;
}
Slide273.2 while
Loop
Condition (2/2)Week5 
27
Output:
?
Week5 
27
CS1010 (AY2012/3 Semester 1)
a = 2;
b = 7;
while (a != b) {
print a;
a = a + 2;
}
Slide283.3 Tracing while
Loop (1/4)
Trace the following codes manually and write out their outputs (assume all variables are of type
int)
Week5 
28
CS1010 (AY2012/3 Semester 1)
a =
1
;
while
(a*a <
100
) {
printf("%d ", a); a *=
2;}
printf
(
"
\n
"
);
(a)
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);
(b)
Slide293.3 Tracing while
Loop (2/4)
Example: Given a positive integer
n, print out its digits from least significant to most significant.
Sample run:
Week5 
29
Enter a positive integer: 289433
49
8
2
CS1010 (AY2012/3 Semester 1)
Slide303.3 Tracing while
Loop (3/4)
Example: Given a positive integer
n, print out its digits from least significant to most significant.
Week5 
30
CS1010 (AY2012/3 Semester 1)
//
Precond
: n > 0
void
print_digits
(
int
n) { int digit;
while
(n >
0
) {
digit = n%
10
;
printf
(
"
%d\n
"
, digit);
n /=
10; }}Week5_Print_digits.c
Slide31//
Precond
: n > 0
void
print_digits
(
int
n) { int digit; while (n >
0
) {
digit = n%
10
;
printf
("%d\n", digit);
n /= 10;
}
}
Week5_Print_digits.c
3.3 Tracing
while
Loop (4/4)
Week5 
31
n initially
28943
n @ point
29843
digit @ point
***
What are the values of
n
and
digit
after exiting the loop?
CS1010 (AY2012/3 Semester 1)
Slide324. The dowhile
Loop (1/2)
Week5  32
do
{ // loop body} while (
condition
);
Execute loop body at least once.cond?
Loop
body
true
false
CS1010 (AY2012/3 Semester 1)
Slide334. The dowhile
Loop (2/2)
Example: Count the number of digits in an integer.
Week5 
33
do
{
// loop body} while ( condition );CS1010 (AY2012/3 Semester 1)
//
Precond
: n > 0
int
count_digits
(
int n
) {
int
counter =
0
;
do
{
counter++;
n /=
10
;
}
while
(n >
0
); return counter;
}
Week5_Count_digits.c
Slide345. The for
Loop (1/2)
Week5 
34
for (
initialization; condition; update
)
{
// loop body}Initialization: initialize the loop variable
Condition:
repeat loop while the condition
on
loop variable
is
true
Update: change value of loop variable
CS1010 (AY2012/3 Semester 1)
Slide355. The for
Loop (2/2)
Example: Print numbers 1 to 10
Week5 
35
int
n;
for (n=1; n<=10; n
++) {
printf
("%3d", n);
}
Steps:
n=1;
if
(n<=10)
{ printf(…);
n
++;
Go to step 2
}
Exit the loop
CS1010 (AY2012/3 Semester 1)
Slide365.1 The for
Loop: Odd Integers (1/2)
Week5 
36
CS1010 (AY2012/3 Semester 1)
#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");}Week5_OddIntegers_v1.c
Slide375.1 The for
Loop: Odd Integers (2/2)
Week5 
37
CS1010 (AY2012/3 Semester 1)
//
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_v2.c
//
Precond
: n > 0
void
print_odd_integers
(
int
n
) {
for
( ; n >
0
; n)
if
(n%2 != 0) printf("%d ", n); printf("\n");}Week5_OddIntegers_v3.cValues printed from largest to smallest.Empty statement
Slide386. 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 ‘while’ loop just for exercise.
Call this program
Week5_SumMultiples3.c
Sample run:Week5  38
Enter a positive integer:
50
Sum = 408
CS1010 (AY2012/3 Semester 1)
Slide396. Exercise #1: Sum of Multiples of 3 (2/2)
How about using a while loop instead?
Pseudocode using a while loop:
Week5 
39
CS1010 (AY2012/3 Semester 1)
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
Slide407. 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 nonpositive, then no asterisk should be printed.
Sample runs:Week5  40
Enter n: 3
*****
Done!
Enter n:
6
***********
Done!
Enter n:
10*******************Done!
Enter n:
2
Done!
Think!
What is the relationship between
n
and the number of *?
CS1010 (AY2012/3 Semester 1)
Slide417. 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
).Week5 
41
CS1010 (AY2012/3 Semester 1)
Pseudocode:read input n ;
if n is nonpositive
print “done” and end program ;
m
compute the number of asterisks given n
print_asterisks
(m)
end program;
Slide428. Common Errors (1/2)
What are the outputs for the following programs?
(Do not code and run them. Trace the programs manually.)
Week5 
42
CS1010 (AY2012/3 Semester 1)
int
i
;
for
(
i
=
0; i
<
10
;
i
++);
printf
(
"
%d\n
"
,
i
);
Week5_CommonErrors1.c
int
i
=
0
;
while
(
i
<
10
);
{
printf
(
"
%d\n", i); i++; }Week5_CommonErrors2.c
Slide438. Common Errors (2/2)
Offbyone 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 
43
CS1010 (AY2012/3 Semester 1)
int
z =
3
;
while
(z = 1) {
printf
(
"z =
%d\n
"
, z);
z = 99;
}
Week5_CommonErrors3.c
Slide449. Some Notes of Caution (1/2)
Involving real numbers
Trace the program manually without running it.
Week5 
44
CS1010 (AY2012/3 Semester 1)
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
Slide459. Some Notes of Caution (2/2)
Involving ‘wraparound’
Trace the program manually without running it.
Week5 
45
CS1010 (AY2012/3 Semester 1)
int
a =
2147483646
;
int
i
;
for
(
i
=
1
;
i
<=
5
;
i
++) {
printf
(
"
%d\n
", a); a++;}Week5_Caution2.c
Slide4610. 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 
46CS1010 (AY2012/3 Semester 1)
Slide4711. 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 
47
CS1010 (AY2012/3 Semester 1)
Slide4811. Using break
in Loop (2/2)
Use ‘break’
sparingly
, because it violates the oneentryoneexit control flow.
A loop with ‘break’ can be rewritten into one without ‘break’.
Week5 
48
CS1010 (AY2012/3 Semester 1)// with break
int
n,
i
=
1
, sum =
0;while (
i <= 5
) {
scanf
(
"
%d
"
, &n);
if
(n <
0
)
break
; sum += n; i++;}
// 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++; }}
Slide4912. Using continue
in Loop
Test out
Week5_ContinueInLoop.c
‘continue’ is used even less often than ‘break’
Week5 
49
CS1010 (AY2012/3 Semester 1)
Slide5013. 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:
Week5  50
Enter a positive integer:
131
131 is a prime.
Enter a positive integer:
713
713 is not a prime.
CS1010 (AY2012/3 Semester 1)
Slide5113. Exercise #4: Prime Number (2/2)
This is your
takehome exercise
.This exercise is mounted on
CodeCrunch.
We will discuss this in the next lecture.
Week5 
51
CS1010 (AY2012/3 Semester 1)
Slide52Summary for Today (1/2)
Week5 
52
Repetition statements (loops)
for
,
while
,
dowhileNested loopsbreak and continueCS1010 (AY2012/3 Semester 1)
Slide53Summary for Today (2/2)
Week5 
53
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 clearVariables should be descriptiveAlgorithm should be efficientCS1010 (AY2012/3 Semester 1)
Slide54Announcements/Thingstodo
Revise Chapter 4 (Lessons 4.7 – 4.11)
Deadline for Lab #2
Deadline: 15
th
September 2012, Saturday, 12noon
Practical
Exam 1 (PE1
)22nd September 2012, SaturdaySee web page for details:http://www.comp.nus.edu.sg/~cs1010/3_ca/pe.html To prepare for next week’s lecture:Read Chapter 5 Functions
Bring along your
Week5_PrimeTest.c
program
Week5 
54
CS1010 (AY2012/3 Semester 1)
Slide55End of File
© 2020 docslides.com Inc.
All rights reserved.