Chapter5 Loops Nva
Chapter5 Loops Nva
Chapter5 Loops Nva
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
Sequence
Repetition
cond? false
true
loop body
Some
statement(s)
false
num >= 0? printf("Enter a number: ");
scanf("%d", &num);
true while (num >= 0) {
printf("You entered: %d\
n", num);
printf …
printf("Enter a number:
printf …
");
scanf …
scanf("%d", &num);
}
return 0;
}
CS1010 (AY2012/3 Semester 1) Week5 - 13
3. The while Loop
false
while ( condition ) cond?
{ true
// loop body
Loop
} body
If condition is true,
execute loop body;
otherwise, terminate
loop.
a = 2; Output: ?
b = 7;
while (a == b) {
print a;
a = a + 2;
}
a = 2; Output: ?
b = 7;
while (a != b) {
print a;
a = a + 2;
}
(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 (AY2012/3 Semester 1) Week5 - 20
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:
while (n > 0) {
digit = n%10;
printf("%d\n",
digit);
n /= 10;
}
}
CS1010 (AY2012/3 Semester 1) Week5 - 22
3.3 Tracing while Loop (4/4)
Week5_Print_digits.c
// Precond: n > 0
void print_digits(int n) {
int digit;
What are the values
while (n > 0) { of n and digit after
digit = n%10; exiting the loop?
printf("%d\n",
digit);
n /= 10;
}
}
n initially 28943
n @ point 28943
digit @ point ***
Loop
body
cond?
true
false
do {
counter++;
n /= 10;
} while (n > 0);
return counter;
}
CS1010 (AY2012/3 Semester 1) Week5 - 26
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 (AY2012/3 Semester 1) Week5 - 27
5. The for Loop (2/2)
Example: Print numbers 1 to 10
int n; Steps:
for (n=1; n<=10; n++) { 1.n=1;
printf("%3d", n);
2.if (n<=10) {
}
printf(…);
n++;
Go to step
2
}
3. Exit the 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
Enter n: 10 Enter n: -2
******************* Done!
Done!
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;
Week5_CommonErrors1.c
int i = 0;
while (i<10);
{
printf("%d\n", i);
i++;
} Week5_CommonErrors2.c
CS1010 (AY2012/3 Semester 1) Week5 - 35
8. Common Errors (2/2)
int z = 3;
while (z = 1) {
printf("z = %d\n", z);
z = 99;
}
Week5_CommonErrors3.c
while (f != 1.0) {
printf("%f\n", f);
f += one_seventh;
}
Week5_Caution1.c
int a = 2147483646;
int i;