Lecture 5 Loops
Lecture 5 Loops
Lecture 5 Loops
OUTLINE
3
Loops
So far our programs are very limited - they can only run
“straight through” the code.
4
A “loop” is a repeated (“iterated”) sequence of
statements.
Like conditionals, loops let us control the flow of our
program in powerful ways.
Like functions, loops take code that has been generalized
and execute it many times.
Block of code
within loop is
known as the
loop body
5
We will study three types of loops:
- while loops
- for loops
- do…while loops
6
• Counter-controlled repetition
– Definite repetition: know how many times
loop will execute
– Control variable used to count repetitions
• Sentinel-controlled repetition
– Indefinite repetition
– Used when number of repetitions not known
– Sentinel value indicates "end of data"
7
• Counter-controlled repetition requires
– The name of a control variable (or loop counter).
– The initial value of the control variable.
– A condition that tests for the final value of the
control variable (i.e. whether looping should
continue).
– An increment (or decrement) by which the control
variable is modified each time through the loop.
8
loop repetition condition
The while loop
The syntax is
while (condition) {
statements; loop body
} Note indentation!
Its meaning is
(a) evaluate the condition
(b) if its value is true (i.e., not zero) do the statements, and go
back to (a)
The while loop will repeatedly execute the statements in
the loop body until the condition is false.
Something in the body of the while loop must change
the condition, or the loop will never end!
9
Steps in using while loop
10
Example - Add five integers:
int i = 0; // initialize i
int temp, sum = 0; // initialize sum
while (i < 5) { // test if i < 5
scanf(“%d”, &temp); // read an integer
sum = sum + temp; // add to sum
i++; // increment i
}
Important to initialize the loop count before starting the
loop, and to increment the count within the loop.
11
Example - Accumulating a sum
sum = 0;
printf("How many numbers? ");
scanf("%d", &number_inputs);
printf("Enter %d numbers: ", number_inputs);
count = 1;
Initialization
while ( count <= number_inputs ) {
scanf("%d", &x);
sum = sum + x; Condition
count = count + 1;
}
Update
12
Example - Calculate pay
13
Example - Computing a Factorial
7! = 1 * 2 * 3 * 4 * 5 * 6 * 7
We could write this without a loop (Yuck!). But easier to
write it with a loop.
x = 1 * 2 * 3 * 4 * 5 * 6 * 7;
printf ( "%d", x ) ;
int i = 1;
int product = 1;
while(i <= 7){
product = product * i;
i++;
}
14
Example - Factorial Function
15
Infinite Loop Using while
while (1)
statement;
next statement;
16
The for Loop
The syntax is
17
If the initialization, condition and/or update parts are
long, place each on a separate line for clarity.
for ( initialization;
condition;
update ) {
statements;
} Execution Steps:
next_statement; 1. initialization
2. condition expression is evaluated.
- if true,
(a) statements are executed.
(b) update expression is executed.
(c) goto step (2) again.
- if false, next statement is executed.
18
for loop versus while loop
i = 0;
while (i < 10) { for(i = 0; i < 10; i++) {
printf(“%d\n”, i); printf(“%d\n”, i);
i++; }
}
19
Which Loop Should You Choose?
20
Example
total_pay = 0.0;
for (count_emp = 0; /* initialization */
count_emp < number_emp; /* loop repetition condition */
count_emp += 1) { /* update */
printf("Hours> ");
scanf("%lf", &hours);
printf("Rate > $");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n\n", pay);
total_pay = total_pay + pay;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);
21
Example - Factorial
int factorial(int n)
{
int i, /* local variables */
product; /* accumulator for product computation */
22
Increments and decrements other than one
23
Infinite Loop Using for
for (;;) {
statements;
}
•Stop the program in the operating system level, for
example, Ctrl-C or Ctrl+Break in DOS.
•There is a break statement for terminating the loop
(discussed later).
•Use carefully!
24
Example - Celsius / Fahrenheit table
#define CBEGIN 10
#define CLIMIT -5
#define CSTEP 5
/* Variable declarations */
int celsius;
double fahrenheit;
26
Conditional Loops
Steps:
27
Loop Design
Sentinel-controlled Loops
29
Endfile-controlled Loops
Input from a file of data and do not know how many data
items there are.
30
Example
sum = 0;
input_status = fscanf(inp, "%d", &score);
while (input_status != EOF) {
printf("%5d\n", score);
sum += score;
input_status = fscanf(inp, "%d", &score);
}
31
Nested Loops
*****
*****
*****
Solution:
repeat 3 times
print a row of 5 *s repeat 5 times
print *
print newline
33
#define ROWS 3
#define COLS 5
…
row = 1;
while ( row <= ROWS ) {
/* print a row of COLS *s */
...
row = row + 1;
}
34
#define ROWS 3
#define COLS 5
row = 1;
while ( row <= ROWS ) {
/* print a row of 5 *s */
col = 1;
while (col <= COLS) {
printf("*"); Outer loop -
Inner loop -
col = col + 1; print three
print one row
} rows
printf( "\n" );
row = row + 1;
}
35
#define ROWS 3
#define COLS 5
outer loop - print 3 rows
...
for ( row = 1; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= COLS ; col = col + 1 ) {
printf(“*”);
}
printf( "\n" ); inner loop - print one
row
}
36
How would you print the following diagram?
*
**
Solution:
***
for every row ( row = 1, 2, 3, 4, 5 ) ****
#define ROWS 5
...
int row, col ;
for ( row = 1 ; row <= ROWS ; row = row + 1 ) {
for ( col = 1 ; col <= row ; col = col + 1)
{
printf( “*” ) ;
}
printf( "\n" );
}
37
Remember the function to print rows of asterisks
between lines of output?
int i, j ;
print (“\n”);
}
}
38
Exercise
Study and execute the following
#include <stdio.h> program.
#define N 7
int main(void)
{
int cnt = 0, i, j, k;
for (i = 0; i <= N; ++i)
for (j = 0; j <= N; ++j)
for (k = 0; k <= N; ++k)
if (i + j + k == N) {
++cnt;
printf("%3d%3d%3d\n", i, j, k);
}
printf("\nCount: %d\n", cnt);
return (0);
}
39
do...while loop
40
41
Example
do {
printf(“Enter your age: “);
scanf(“%d”, &age);
} while (age < 0);
42
Example
counter = 1;
do {
printf( "%d ", counter );
} while (++counter <= 10);
sum = 0;
do {
sum += n % 10;
n /= 10;
}
while(n > 0);
45
Controlling Repetition …
break and for #include <stdio.h>
Causes an exit from the innermost enclosing loop. int main(void)
46
Controlling Repetition …
continue
Causes the current iteration of
a loop to stop, and begins
the next iteration.
#include <stdio.h>
#define MAX 5
int main(void)
{
int data, sum=0, k;
for (k=0; k<MAX; k++) {
scanf ("%d", &data); 10
if (data <= 0) 20
continue;
-1
sum += data;
} 90
printf ("Sum of positive values is %d\n.", sum); -5
return (0); Sum of positive values is 120.
}
47
How to debug and test programs
• Debugger Program
– Single-step execution (F8)
– Add Watch-window (Alt+W W)
– Breakpoints
• Debugging without a debugger
– Insert additional diagnostic calls to printf to trace the values
of critical values
#define DEBUG 0
if (DEBUG)
printf ……
48
Common Programming errors
sum+= i;
50
Common Programming errors …
• Be careful when testing for inequality (!=) to
control repetition of a loop (infinite loop may
result)
• In sentinel-controlled loop:
– Provide a prompt to program’s user what value to
enter as sentinel
– Make sure that the sentinel value cannot be
confused with a normal data item
• Do not mistype equality test (==) and
assignment operator (=)
51