0% found this document useful (0 votes)
23 views42 pages

07. Looping (III)

Uploaded by

0987987972
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views42 pages

07. Looping (III)

Uploaded by

0987987972
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Looping (III)

Outline
• Motivation
1. More Examples
2. Nested Loops – A loop inside another loop
3. Common Mistakes of Nested Loops
4. A Challenging Example (Selection Sort)
5. Break and continue

2
Motivation
• In our previous lectures, we have learned how to
use while loop and for loop.

• We now move to more advanced usage of loops.

• Loops are VERY IMPORTANT as they enable


solutions and algorithms for many problems.

3
1. More Examples (Example #1)
• Read 100 integers between 1 and 10 (inclusive) from the
user and output the frequency of each number.
1 // freq[x-1] will store the frequency of x, where x =
2 1,…,10
3 int freq[10] = { 0 }; // Initialize all elements to
4 0
5 int i, input;
6
7 for (i = 0; i < 100; i++) {
8 scanf("%d", &input);
9
10 // Assume all inputs are between 1 and 10
11 (inclusive)
12 freq[ input - 1 ]++; // corresponding to counters
13 [0]-[9]
}
4
for (i = 0; i < 10; i++)
1 // freq[x-1] will store the frequency of x, where x =
21. More Examples (Example #1)
1,…,10
3 int freq[10] = { 0 }; // Initialize all elements to
4 0
5 int i, input;
6
7 for (i = 0; i < 100; i++) {
8 scanf("%d", &input);
9
10 // Assume all inputs are between 1 and 10
11 (inclusive)
12 freq[ input - 1 ]++; // corresponding to counters
13 [0]-[9]
}
6 Frequency of 1: 0
8 for (i = 0; i < 10; i++) Frequency of 2: 20
4 ...
printf("Frequency
100 inputs of %d: %d\n", i+1, freq[i]);
6 Frequency of 9: 45
5 Frequency of 10: 1
...
5
1. More Examples (Example #2)
• Read 100 integers between 1 and 100 (inclusive) from a
user and output the frequency of the numbers falling into
these ranges: 1~10, 11~20, 21~30, …, 91~100

• In this example, we can map the input to the array index as


f(x) = 0, if 1 ≤ x ≤ 10
1, if 11 ≤ x ≤ 20

9, if 91 ≤ x ≤ 100
or

f(x) = (x - 1) / 10 (note: integer division)

• In loops, it is always important to determine the trend!


6
1. More Examples (Example #2)
1 int freq[10] = { 0 }; // Initialize all elements to
2 0
3 int i, input, index;
4
5 for (i = 0; i < 100; i++) {
6 scanf("%d", &input);
7
8 // Assume all inputs are between 1 and 100
9 (inclusive)
10 index = (input – 1) / 10;
11 freq[ index ]++;
12 }
13
14 for (i = 0; i < 10; i++)
15 printf("Frequency of %d-%d: %d\n",
16
(Ask i*10 How
yourself: + 1,do
i*10
the+input
10, freq[i]);
and output look like?)

7
1. More Examples (Example #2)
11
12 for (i = 0; i < 10; i++)
13 printf("Frequency of %d~%d: %d\n",
14 i*10 + 1, i*10 + 10, freq[i]);
15
Dry-running this loop…
i i*10+1 i*10+10 freq[i]
---------------------------------------------
-----
0 1 10 the count
for 1~10
1 11 20 the count
for 11~20
...
9 Observe
91 how these numbers 100 the count
for 91~100are generated from i
8
2. Nested Loops – A Loop Inside Another Loop
1 int i, j; 1 1
2 for (i = 1; i <= 3; i++) { 1 2
3 for (j = 1; j <= 4; j++) { i = 1
1 3
4 printf("%d %d\n", i, j); 1 4
5 } 2 1
6 } 2 2
i = 2
2 3
2 4
• For each outer loop iteration, the 3 1
inner loop iterates for 4 times. 3 2
i = 3
– Total # of printf() = 3 * 4 = 12 times 3 3
3 4
• The whole loop is considered as only ONE
statement, i.e. no semi-colon (;) required ↑↑
i j

9
2.1. Outer Loop and Inner Loop(s)
• A nested loop always has an outer loop and one or
more inner loops

• Assuming a simple nested loop of 2 levels


– Outer loop represents repetition at the topmost level
– The inner loop represents a repetition that repeats in
every outer loop

10
2.1. Outer Loop and Inner Loop(s)
• A good example would be your university life, which
involves nested repetition:
– You will likely study for 4 years
– Each year you will have 2 semesters (simplified)
– Each semester you will have 13 weeks of study (simplified)

• Question: Which one of them is the outer loop? Inner


loop(s)?

11
2.1. Outer Loop and Inner Loop(s)
1 int year, sem, week;
2 for (year = 1; year <= 4; year++) {
3 printf("Year %d\n", year);
4 }
5
6
7
8
9 The outer loop is obviously
the 4 years you will spend
10 in the university. In the
example above, we model
your 4 years of university
life in C.

12
2.1. Outer Loop and Inner Loop(s)
1 int year, sem, week;
2 for (year = 1; year <= 4; year++) {
3 for (sem = 1; sem <= 2; sem++) {
4 printf("Year %d sem %d\n", year, sem);
5 }
6 }
7
8
9 In each year, you will have
2 semesters. So the
10 repetitions of semester is
modelled by the inner loop
here.

13
2.1. Outer Loop and Inner Loop(s)
1 int year, sem, week;
2 for (year = 1; year <= 4; year++) {
3 for (sem = 1; sem <= 2; sem++) {
4 for (week = 1; week <= 13; week++) {
5 printf("Year %d sem %d week %d\
6 n",year,sem,week);
7 }
8 }
9 } If we go further, we have roughly
13 weeks in each semester. So
10 we can have a further inner loop
to the semester loop. This makes
our nested loop a 3-layer one.

14
2.2. Nested Loops (Example #1)
• Objective: To output a multiplication table in the
following format:

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
9 rows ......
9 18 27 36 45 54 63 72 81
90

• What are the things being repeated?


– There are 9 rows (outer loop)
– Each row contains 10 numbers (inner loop)

15
2.2. Nested Loops (Example #1)
1 int i, j;
2 for (i = 1; i <= 9; i++) { // 9 rows
3
4 for (j = 1; j <= 10; j++) { // 10 numbers
5 per row
6 printf("%d ", ______________);
7 }
8
9 printf("\n"); // Newline appears only once per
row
• What
} expression, in terms of i and j, will yield the
numbers we need?

16
2.2. Nested Loops (Example #1)
1 int i, j;
2 for (i = 1; i <= 9; i++) { // 9 rows
3
4 for (j = 1; j <= 10; j++) { // 10 numbers
5 per row
6 printf("%d ", i * j);
7 }
8
9 printf("\n"); // Newline appears only once per
row
• Often,
} the numbers we want to generate inside a loop (or
nested loops) can be expressed in terms the loop
variables.

17
2.3. Nested Loops (Example #2)
1 // A and B represent two 3x3 matrices
2 int A[3][3] = { { 1, 2, 3 }, { 0, -1, 2 }, { 0, 0, 1 } };
3 int B[3][3]; // To store the transpose of matrix A
4 int i, j;
5
6 // Store transpose of A in B
7 for (i = 0; i < 3; i++)
8 for (j = 0; j < 3; j++) Example: Using a nested loop to
9 B[i][j] = A[j][i]; handle a 2D array
10
11 // Print matrix A
12 for (i = 0; i < 3; i++) {
13 for (j = 0; j < 3; j++)
14 printf("%4d", A[i][j]); 1 2 3
15 printf("\n"); 0 -1 2
16 } 0 0 1
17 printf("\n");
18 1 0 0
19 // Repeat the above for-loop for matrix B 2 -1 0
20 ... 3 2 1 18
2.4. Nested Loops (Example #3)
• Objective: Given a positive integer N, output a triangle in
the following format (e.g., when N = 5):

*
**
N rows ***
****
****
*
N columns

19
2.4. Nested Loops (Example #3)
1 int i, j, N;
2
3 printf("N = ? ");
4 scanf("%d", &N);
5
6 for (i = 1; i <= N; i++) { // N rows
7
8 To write a nested loop, we first need to
consider what constitutes our outer
9 loop.
10
11 } In this example problem, we need to
print a total of N lines, so an outer loop
to count for N times would be good.

20
2.4. Nested Loops (Example #3)
1 int i, j, N;
2
3 printf("N = ? ");
4 scanf("%d", &N);
5
6 for (i = 1; i <= N; i++) { // N rows
7 // Step 1: print i number of stars
8 // i.e. 1 star in line 1, 2 stars in line 2...
9 etc.
10 // Step 2: print a new line character
Then we think about what to do in our
11 inner loop. In this case, we need an
} inner loop to print the number of stars
according to the line number.
We also need to print a new line
character after finishing each row.

21
2.4. Nested Loops (Example #3)
1 int i, j, N;
2
3 printf("N = ? ");
4 scanf("%d", &N);
5
6 for (i = 1; i <= N; i++) { // N rows
7 for (j = 1; j <= i; j++) { // row #i has i
8 stars
9 printf("*");
10 This is already the solution.
}
11 printf("\n");
N = ? 6 For beginners, always make sure you
} * plan for the outer loop and inner loop
** before you start writing your code or
*** pseudocode.
****
*****
****** 22
2.5. Nested Loops (Example #4)
• Objective: To find all sets of integers that satisfy the
following equality:
x2 + y2 + z2 = 1000000, 0 ≤ x, y, z ≤ 1000

• One possible (quick and dirty) solution is to try all


possible values for x, y, and z.

23
2.5. Nested Loops (Example #4)
1 int x, y, z;
2
3 for (x = 0; x <= 1000; x++) {
4 for (y = 0; y <= 1000; y++) {
5 for (z = 0; z <= 1000; z++) {
6 if (x*x + y*y + z*z == 1000000)
7 printf("%d, %d, %d\n", x, y, z);
8 }
9 }
10 }

24
3. Nested Loop Common Mistakes
• Always use a different index in each layer of nested
loops
– By convention we often use i, j and k
– What happens if you mistakenly used the same index for
different layers of a nested loop? Check out a modified
Example #1 below:
int i, j;
for (i = 1; i <= 3; i++) {
for (i = 1; i <= 4; i++) Can
{ you dry run the
program to see the
printf("%d\n", i); expected output?
}
}

25
3. Nested Loop Common Mistakes
• Be aware of the placement of new lines
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= i; j++) {
printf("*");
} When should the output
} finish printing a line?
printf("\n");
• Indentation and relationship between loops
for (i = 1; i <= 3; i++)
for (j = 1; j <= i; j++) {
...
}
} // where does this } come from??
26
4. Challenging Example (Selection Sort)
• Selection Sort is a sorting method that involves a
simple 2-layer nested loop
• Selection Sort is among the first algorithm you
learn in this course

• An algorithm is a set of instructions that one can


follow to solve a general set of problems

27
4. Challenging Example (Selection Sort)
int A[6] = { 4, 5, 7, 2, 9, 1 };
Iteration # Step 1: Subarray to be Step 2: Locate the Step 3: Swap the
processed: N=6 smallest # in the smallest # with
A[i] … A[N-1] sub-array A[i]

i=0 457291 457291 157294


i
i=1 157294 157294 127594
This part is sorted!

i
i=2 127594 127594 124597
i
i=3 124597 124597 124597
i
i=4 124597 124597 124579
i

28
4. Challenging Example (Selection Sort)
// Pseudocode:
// Given an array A[] of size N

for i = 0 to N-2 { //step 1


minPos = position of the smallest element
among A[i] … A[N-1]; //step 2

Swap A[i] with A[minPos]; //step3


}

// Note: When there is only one element left, we do not


// need to perform the steps in the loop.
// Therefore, the loop only needs to iterate
// N-1 times (i.e., from 0 to N-2).

29
1 // Suppose A[] contains N numbers. The following
2 segment of
3 // code sorts the data in the array so that
4 // A[0] <= A[1] <= ... <= A[N-2] <= A[N-1]
5
6 int i, j, minPos, tmp;
7 for ( i = 0; i < N-1; i++ ) { //step1
8
9 // Locate the smallest element among A[i] … A[N-
10 1],
11 // and store the location of it in
12 minPos. //step2
13 minPos = i;
14 for ( j = i+1; j < N; j++ )
15 if ( A[ j ] < A[ minPos ] )
16 minPos = j;
17
18 // Swap A[i] with A[minPos] only if necessary
19 //step3
20 if (minPos != i) {
21 tmp = A[ i ];
22 Challenging
A[ Example
i ] = (Selection
A[ minPos Sort) ]; 30
More Exercise
• Suppose now I want to write a C program to
compute and find out all prime numbers in the
range of 2 to 1000
• How are you going to tackle the problem?
– What will be our outer loop?
– How about our inner loop?
• Hint: In this case, you can first write your inner
loop first and make sure it is correct before you
proceed with the outer loop.

31
5. Break and continue
• break statement

• continue statement

32
5.1. What is break?
for (init; LoopCondition;
update) {
statement1;
if (BreakCondition)
break;
init statement2;
}
statement2 & statement3;
update
false

Loop Break
Condition Condition
true true
Early Exit in a Loop
false statement1
The break statement, when
executed, causes the program to
statement3 leave the closest enclosing loop
immediately.

33
5.2. Examples of break statement
1 int input, sum = 0; // To store input value and their
2 sum
3
4 while (1) { // Use "break" to stop the loop
5 instead
6
7 printf("Input: ");
8 scanf("%d", &input);
9
10 if (input == 0)
11 break; // Loop will stop when input value
12 is 0
13
14 sum = sum + input; Rewriting the example
from Looping (I).
15 }

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


5.2. Examples of break statement
• Using break to stop a for loop
1 int i;
2
3 for (i = 0; i < 10; i++) {
4 if (i == 3)
5 break; 0
6 1
2
7 printf("%d\n", i); Bye!
8 }
9
10 printf("Bye!\n");
11

35
5.2. Another Example
To compare if two arrays have the same content, we need to compare
their elements one by one. As soon as we encounter the first
difference between the two arrays, we can stop early using break!
1 int A[10], B[10], i;
2 int hasSameContent;
3 … // Suppose A and B are assigned some values
4 here
5
6 hasSameContent = 1; // Assume they have the same
7 content
8 for (i = 0; i < 10; i++) {
9 if (A[i] != B[i]) {
10 hasSameContent = 0; // a counter-example is
11 found!
12 break;
36
13 }
5.3. What is continue?
for (init; LoopCondition;
update) {
statement1;
if (continueCondition)
continue;
init statement2;
update
}
statement3;
statement2
false true
Loop Continue
Condition
Continuation in a Loop
Condition
true
The continue statement, when
false statement1
executed, causes the program to skip
the remaining statements in the
statement3 closest enclosing loop for the
current iteration.

37
5.4. Examples of continue statement
• for-loop version
1 int i;
2
0
3 for (i = 0; i < 10; i++) { 1
4 if (i == 3) 2
5 continue; 4
6 5
6
7 printf("%d\n", i); 7
8 } 8
9 9
10 printf("Bye!\n"); Bye!
11

38
5.3. What is continue?
while ( LoopCondition ) {
statement1;
if (continueCondition)
continue;
statement2;
init }
statement3;

statement2
false true
Loop Continue
Condition Condition
true

false statement1

statement3
The while-loop version

39
5.4. Examples of continue statement
• while-loop version
1 int i;
2 0
1
3 i = 0; 2
4 while (i < 10) { 4
5 if (i == 3) { 5
6 i++; 6
7
7 continue;
8
8 } 9
9 printf("%d\n", i); Bye!
10 i++;
11 }
The i++ at line 10 will be skipped when
12 printf("Bye!\n"); continue is executed. Without the i++ at line
6, the loop will iterate forever.

40
Summary
• More examples on looping

• Nested loops
– Syntax and examples
– Common mistakes
– A challenging example: selection sort

• break and continue

41
Reading Assignment
• C: How to Program, 8th ed, Deitel and Deitel
• Chapter 3 Structured Program Development in C
– Sections 3.7 – 3.10
• Chapter 4 C Program Control
– Sections 4.1 – 4.6, 4.9

42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy