0% found this document useful (0 votes)
13 views

05a. Looping (I)

Uploaded by

0987987972
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

05a. Looping (I)

Uploaded by

0987987972
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

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.

• Loop statements allows some tasks to be executed


repeatedly zero or more times.

• In our previous lectures, we have seen many cases


in which we need to repeat certain actions again
and again.

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

What if we want to enter 40 numbers?! Isn't that very silly to


copy and paste a very similar statement 40 times? 4
1. while Statement (Syntax)

while (condition) condition


statement1; statement1
statement2; false true

statement2

• Repeatedly execute statement1 as long as condition is


true.

• When condition is false, execute statement2.


5
1.1. while Statement (Example #1)
1 int i;
2
3 i = 1;
4
5 // A simple loop that iterates 5 times
6 while (i <= 5) {
7 printf("%d\n", i);
8 i++; // i=i+1;
9 }
1
10 2
11 printf("Lastly, i = %d\n", i); 3
12 4
5
Lastly, i = 6

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!

After the loop ends, C will In this loop, we hope to generate


continue to execute the i==0, i==1, i==2, i==3 in
statements ahead. this order. 11
Rewriting Example #1
If you execute the program, this is
1 int list[4]; the order of execution:
2 First time executing the loop body:
3 printf("Enter 4 #'s: "); scanf("%d",&list[i]); // i
4 int i = 0; == 0
5 while (i <= 3) { i++; // i == 1
6 scanf("%d",&list[i]); Second time:
7 i++; scanf("%d",&list[i]); // i
== 1
8 }
i++; // i == 2
9
Third time:
10 printf("You have entered (in reverse):");
scanf("%d",&list[i]); // i
11 printf("%d %d %d %d\n", list[3],
== 2 list[2], list[1],
list[0]); i++; // i == 3
Now the four scanf() lines Forth time:
scanf("%d",&list[i]); // i
work the same as in the original
== 3
Example #1, and you can expect i++; // i == 4
the same behaviour as before.
12
When returning to line 5, the loop will stop
2. How to Use Loops
• Loops can help us in many different daily
computing tasks.
• As a beginner, you will need to at least know two
basic looping cases:
– Basic Case #1: Repeat a task a finite number of times
(as in Example #1)
– Basic Case #2: Repeat a task indefinitely until a
condition is met

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.

• Let's look at two slightly more complex situations


that will be challenging to new learners of looping.

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.

• Looping will be our best tool to achieve this,


although it does not appear to be a repetitive task
from the first sight.

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.

• If you put them into the wrong place, the program


won't work!

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.

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 sum = sum + input;
8 average = sum / 4; // how many times does this
9 execute?
10 i++;
11 }
12 printf("Average of 4 numbers is %.2f\n", average);
13
14 24
3.1. Using Repetition for Statistics Generation
How about this? Hint: It will generally give a wrong answer as well. Do you see
why?
1 printf("Enter 4 #'s: ");
2 int i = 0;
3 int input;
4 double average, sum;
5 while (i <= 3) {
6 sum = 0;
7 scanf("%d", &input);
8 sum = sum + input;
9 i++;
10 }
11 average = sum / 4;
12 printf("Average of 4 numbers is %.2f\n", average);
13
14 25
3.2. Using Loop Variables in Computation
• In some cases, we use the loop variable directly in
our computations
• In such cases, we do not just care about how many
times we are repeating, we also care about how
the loop variable changes from the initial value to
the final, terminating value

• We have already seen it in action in Example #1

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 3210
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

• When you write a loop or debug a loop, you have


at least these TWO things to check:
– Structurally
• It should have loop variable initialization, looping condition
and loop condition update
– Logically
• You should make sure statements before/inside/after the
loop are in the right place
32
5. A More Complicated Example

• Given the following task:


– Step 1. Ask the user for a number.
– Step 2. If the input is not zero, add the new input to the sum
all previous inputs. Then, go back to Step 1.
– Step 3. If the input is zero, print the sum of all inputs and
terminate the program.

• How can we transform it into a while-loop program?


• First: What basic loop case is involved?
– Basic Case #2 – Indefinite repetition
– It also involves statistics generation
33
5. A More Complicated Example
• Let's plan for the looping
• Before the Loop:
What do we need to do ONCE before entering loop?
– We need to set a loop condition variable that indicates whether the user has
input zero
– We also need to initialize a variable to store the sum
• Inside the Loop:
What needs to be repeated?
– We will ask for input from user
– We need to check if it is zero
– We need to add input to sum
• After the Loop:
What needs to be done AFTER everything is finished?
– Print out the sum, of course!
34
5. A More Complicated Example
• Transforming Steps 1 – 3 to a flow chart:
Ask user for a
number
Step 1

Is the input Print the sum of all


YES
== 0? inputs
Step 3
Go back NO
to Step 1
Add new input to
the sum of all Program terminates
numbers
Step 2 Step 3

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 }

printf("Sum = %d\n", sum); 36


5. A More Complicated Example
1 int input, sum = 0; // To store input value and their
2 sum Loop variable
initialization
3 int getZero = 0; // For controlling the loop;
4 // 1 => stop loop; 0 => continue
5 iterate Loop condition
6
7 while (getZero == 0) {
8 printf("Input: ");
9 scanf("%d", &input); Loop condition
10 update (conditionally )
11 if (input == 0)
12 getZero = 1;
13 else Again, all components of a loop
14 sum = sum + input; are included.
15 }

printf("Sum = %d\n", sum); 37


5. A More Complicated Example
1 int input, sum = 0; // To store input value and their
2 sum Before the loop
3 int getZero = 0; // For controlling the loop;
4 // 1 => stop loop; 0 => continue
5 iterate Inside the loop
6
7 while (getZero == 0) {
8 printf("Input: ");
And the C program matches our
9 scanf("%d", &input); previous planning!
10
11 if (input == 0)
12 getZero = 1;
13 else
14 sum = sum + input; After the loop
15 }

printf("Sum = %d\n", sum); 38


6. Infinite Loop

• A loop that never stops. e.g.,


while (1)
printf("Hello!\n");

• Usually introduced by mistakes.

• What could happen when a program runs into


an infinite loop?
39
6.1. Common Mistakes that Result in Infinite Loops

• A condition that is always true:


while (a > -10 || a < 10) {

}

• Failing to update/modify the value of the loop variable in the


loop:
i = 0;
while (i <= 5) {
printf("i = %d\n", i);
}
– In this example, i is always 0.
40
6.1. Common Mistakes that Result in Infinite Loops
• Using = instead of == as equality operator
while (a = 1) {
...
}
– Variable a is assigned 1 and the whole expression is evaluated to
1, and 1 means true.

• Placing ';' after the condition of a while loop


while (a != 0);
{ ; here represents an empty statement. That is
… while (a != 0);
} is interpreted the same as
while (a != 0) {
} 41
Summary
• Syntax of while loops
• Using repetition to solve problems
• How to plan for a loop
• Common mistakes and infinite loops

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

You might also like