05a. Looping (I)
05a. Looping (I)
Outline
• Motivation
1.while Statement (Syntax)
2. How to Use Loops
3. Using Repetition to Solve Problems
4. Tips on Planning to Write a Loop
5. A More Complicated Example
6. Infinite Loop
2
Motivation
• if-else (branching) statements allows some
statements to be executed zero or one times.
3
Example #1 (Motivating Example)
1 int list[4];
2
3 printf("Enter 4 #'s: ");
4 scanf("%d", &list[0]);
5 scanf("%d", &list[1]);
Only the array index is
6 scanf("%d", &list[2]);different in each line
7 scanf("%d", &list[3]);
8
9 // Print the input values in reverse order
10 printf("You have entered (in reverse): ");
11 printf("%d %d %d %d\n", list[3], list[2], list[1],
list[0]);
Enter 4 #'s: 5 12 6 1110
You have entered (in reverse): 1110 6 12 5
statement2
6
1.2. Key Components of a Loop
1 int i; 4. "Loop variable" initialization
2
3 i = 1; Assign a value to the variable that is used in the loop
4 condition to make the loop condition true initially.
5 // A simple loop that iterates 5 times
6 while (i <= 5) {
1. Loop condition
7 printf("%d\n", i);
8 i++; - When this condition is true, the
9 } loop body is executed.
- Usually controlled by a variable.
10
11 3. Change of loop condition
printf("Lastly, i = %d\n", i);
12 2. Loop body
To stop the loop, we need to make the
loop condition false. This can usually be
done by changing the loop variable. Statements to be repeated.
You should never omit this!
7
Rewriting Example #1
1 int list[4];
2 We can use a while loop to
3 printf("Enter 4 #'s: "); help us!
4 scanf("%d", &list[0]); We want to repeat the
5 scanf("%d", &list[1]); statement for multiple times,
6 scanf("%d", &list[2]); starting with index 0, then 1,
7 scanf("%d", &list[3]); then 2, then 3
8
9 // Print the input values in reverse order
10 printf("You have entered (in reverse): ");
11 printf("%d %d %d %d\n", list[3], list[2], list[1],
list[0]);
8
Rewriting Example #1
1 int list[4];
2
3 printf("Enter 4 #'s: ");
Let's rewrite our program.
4 int i = 0; We first create a variable i to
5 store the index of the array
6 list.
7 We said we would start from 0,
8 so we set i = 0.
9
10 This is our loop variable
11 initialization.
9
Rewriting Example #1
1 int list[4];
2
3 printf("Enter 4 #'s: "); Let's create the loop and the
4 int i = 0; loop condition.
5 while (i <= 3) {
6 We said we want to end when
7 i == 3,
8 }
so we should loop as long as i
9
is less than or equal to 3.
10
11
Notice how we have used the
braces {} to mark the loop
body first, which is currently
empty.
10
Rewriting Example #1
1 int list[4];
2
3 printf("Enter 4 #'s: "); Now we will fill up the loop body!
4 int i = 0;
5 while (i <= 3) {
We get an integer from user, and
6 scanf("%d",&list[i]);
then put it into the ith slot in the
7 i++;
8 }
array.
9
10 Remember
printf("You have entered (in to increase
reverse): "); i by 1
11 every time
printf("%d %d %d %d\n", list[3], you loop!list[1],
list[2], The change
list[0]); of looping condition is a must!
13
2.1. Basic Case #1: Finite Repetition
Extending from Example #1, we can also use another loop to print out the
contents of the array; we will do it 4 times, which is finite.
1 int list[4];
Are you able to identify the:
2 printf("Enter 4 #'s: ");
• loop variable initialization,
3 int i = 0;
• looping condition,
4 while (i <= 3) {
5 scanf("%d",&list[i]);
• loop condition change, and
6 i++; • loop body?
7 }
8 printf("You have entered (in reverse):");
9 int j = 3; // let's print in reverse
10 while (j >= 0) {
If you write down the repeated
11 printf("%d ",list[j]);
printf(), you will see why you
12 j--;
can again expect the same behaviour
13 }
as the original Example #1
14 printf("\n"); 14
2.1. Basic Case #1: Finite Repetition
i, j, k are commonly used as loop variables, and
are often referred to as counters in finite loops. Let's have an exercise:
Can you dry run and
1 int list[4];
explain to yourself how
2 printf("Enter 4 #'s: ");
the loop executes?
3 int i = 0;
4 while (i <= 3) {
5 scanf("%d",&list[i]); Loop #1 You can see there are
6 i++; two loops here. Why
7 } do we need two loops?
8 printf("You have entered (in reverse):");
9 int j = 3; Can we use only one to
// let's print in reverse
10 while (j >= 0) { achieve the same
11 printf("%d ",list[j]); Loop #2 effect?
12 j--;
13 }
14 printf("\n"); 15
2.2. Basic Case #2: Indefinite Repetition
In this example, we will keep asking the user for a number until the input is –1;
we do not have a fixed or finite number of repeats in mind.
Our loop condition variable is NOT a counter
this time: the loop condition variable is the
1 int input = 0; user input.
2 We conveniently set it to 0 first to make sure
3 while (input != -1) { that the loop will start.
4 scanf("%d", &input);
5 printf("You have input %d\n", input);
6 } How many times will the loop
7 execute? Do you really know?
8 printf("Last input is %d, the loop has ended\n",
9 input);
5
You have input 5
-1
You have input -1
16
Last input is -1, the loop has ended
2.2. Basic Case #2: Indefinite Repetition
• You cannot rewrite the above example without
using loops.
– The user can theoretically go on and input numbers
forever, indefinitely (!)
– This is very common in real life computing applications:
users can continue something indefinitely until they
want to stop.
• Looping enables us to write programs with a
flexible repeating behavior.
17
3. Using Repetition to Solve Problems
• As long as a solution requires multiple steps that
are the same or very similar to each other, we can
use looping to help us.
18
3.1. Using Repetition for Statistics Generation
• When you need to generate statistics and insights
from a set of data, you often need to go through
each piece of data one by one.
– E.g., sum, average, maximum, minimum, etc.
19
3.1. Using Repetition for Statistics Generation
Here we want to ask for several inputs from the user and print the
average value out: Let's first start with writing a C
1 printf("Enter 4 #'s: "); program to ask for several inputs
2 int i = 0; from the user.
3 int input;
4 Here we see the proper
5 while (i <= 3) {
loop variable initialization,
6 scanf("%d", &input);
looping condition, and
7 ...
8 i++;
loop variable change
9 }
10 ...
11 printf("Average of 4 numbers is %.2f\n", average);
12
13
14 20
3.1. Using Repetition for Statistics Generation
To calculate the average, we need
to add up the input to a sum.
1 printf("Enter 4 #'s: "); We will want to
2 int i = 0; 1) initialize sum to be 0,
3 int input; 2) add up each input to the sum,
4 double average, sum = 0.0;and finally
5 while (i <= 3) { 3) calculate the average from
6 scanf("%d", &input); the sum after all inputs are
7 sum = sum + input; considered.
8 i++;
9 }
The added statements are in red.
10 average = sum / 4;
11 printf("Average of 4 numbers is %.2f\n", average);
12 Question:
Enter 4 #'s: 7 11 45 23 input is int, why do
Average of 4 number is 21.50 we use double for sum?
21
3.1. Using Repetition for Statistics Generation
• To generate statistics, we usually need to set up
another variable (NOT the looping variable) to
aggregate the data. In the previous example, it is sum.
– Such variables should be initialized BEFORE the loop.
– Such variables must be updated INSIDE the loop.
– Such variables are usually only useful AFTER the loop ends.
22
3.1. Using Repetition for Statistics Generation
What will be the result of this modified program? Hint: It will generally give an
unexpected answer!
1 printf("Enter 4 #'s: ");
2 int i = 0;
3 int input;
4 double average, sum = 0.0;
5 while (i <= 3) {
6 scanf("%d", &input);
7 i++;
8 }
9 sum = sum + input;
10 average = sum / 4;
11 printf("Average of 4 numbers is %.2f\n", average);
12
13
14 23
3.1. Using Repetition for Statistics Generation
How about this one? Hint: this is rather a performance issue.
26
3.2. Using Loop Variables in Computation
1 int list[4];
2 printf("Enter 4 #'s: "); We have two loops here.
3 int i = 0; In both loops, we repeat exactly
4 times.
4 while (i <= 3) {
5 scanf("%d", &list[i]); 0 However, in loop #1, the loop
6 i++; 1 variable changes in this way:
2 0 1 2 3.
7 } 3
8 printf("You have entered (in reverse):");
In loop #2, we use the loop
9 int j = 3; // let's print in reverse
variable as an index to access
10 while (j >= 0) { the array, and we wish to access
11 printf("%d ", list[j]); 3 in reverse. The loop variable
12 j--; // j=j-1; 2 changes in this way:
1 3210
13 }
0
14 printf("\n");
27
3.2. Using Loop Variables in Computation
1 int list[4];
2 printf("Enter 4 #'s: "); If we alter our loop variable
3 int i = 0; in loop #2 to change in this
4 while (i <= 3) { way:
5 scanf("%d", &list[i]); 0 1 2 3,
then we are still repeating 4
6 i++;
times, BUT we will NOT be
7 }
printing the list in a reverse
8 printf("You have entered (in reverse):");
order.
9 int j = 0;
10 while (j <= 3) { How the loop variable
11 printf("%d ", list[j]); 0 changes IS IMPORTANT in
12 j++; 1 here because we use the
13 } 2 loop variable directly in our
3 calculation (array index).
14 printf("\n");
28
3.2. Using Loop Variables in Computation
1 int list[4];
2 printf("Enter 4 #'s: "); Note that we can print in
3 int i = 0; reverse order again, if we
4 while (i <= 3) { use 3-j instead of j to
5 scanf("%d", &list[i]); access the array.
6 i++;
Do you understand why? Can
7 }
you dry-run the loop and
8 printf("You have entered (in reverse):");
see?
9 int j = 0;
10 while (j <= 3) { Some people prefer the
11 printf("%d ", list[3-j]);
3 complexity to be with the
12 j++; 2 loop variable preparation,
13 } 1 yet some prefer it with the
0 computation later.
14 printf("\n");
29
3.2. Using Loop Variables in Computation
Another example of using loop variable directly in computation, in
which we add from 1 to N, where N is a positive integer from user.
1 int N;
2
3 scanf("%d", &N);
4
5 int i = 1; // our loop variable
6 int sum = 0;
7 while (i <= N) {
8 sum = sum + i;
9 i++;
10 }
11
12 printf("1 + .. + %d = %d\n", N, sum);
5
13
1 + .. + 5 = 15
14 30
4. Tips on Planning to Write a Loop
• Before you write a loop, please make sure you figure
out:
– Before the Loop
What should be done before the loop?
• You almost always need to initialize the looping variable(s)
• You may need to initialize the variables that persists through
your repetition
– Inside the Loop
What should be done repeatedly?
And how should the loop variable change?
– After the Loop
What should be done after all repeats are finished?
31
4.1. Tips: Debugging a Loop
• Your loop will be wrong if you are confused with
what you should do Before/Inside/After the loop
35
5. A More Complicated Example
1 int input, sum = 0; // To store input value and their
2 sum
3 int getZero = 0; // For controlling the loop;
4 // 1 => stop loop; 0 => continue
5 iterate
6
7 while (getZero == 0) { Input: 1
8 printf("Input: "); Input: 3
Input: 5
9 scanf("%d", &input);
Input: 7
10 Input: 0
11 if (input == 0) Sum = 16
12 getZero = 1;
13 else
14 sum = sum + input;
15 }
42
Reading Assignment
• C: How to Program, 8th ed, Deitel and Deitel
• Chapter 3 Structured Program Development in C
– Sections 3.7 – 3.9
• Chapter 4 C Program Control
– Sections 4.1 – 4.3
43