4️⃣

6.4 Nested-Loops

 

Nested Loops

Now that we have gone over the different types of loops that you can use in C, let’s talk more about how you can use them. Nested loops are a type of structure you can use by coding a loop inside of another loop. You can use nested loops in order to code tables such as a multiplication table. Let’s go over an example:
 
for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { printf(“%d\t”, (i*j)); } printf(“\n”); }
 
In the above example, we have used 2 for loops to create a multiplication table for the numbers between 1 and 10. The first for loop iterates through each number from 1 through 10, increasing i by 1 every iteration. The second for loop, which is inside the first for loop, has the same for loop header as the first for loop, except it uses a different variable, j. Inside this for loop, the computer prints out the product of i and j. The second for loop is repeated 10 times with every 1 iteration of the first for loop. After the computer is done reading through the second for loop, it prints a new line before going back to the first for loop. So, essentially, by the time this program has completely finished executing, the first for loop will have ran 10 times and the second for loop will have ran 100 times. Here is what the output should look like:
 
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100
 

Previous Section

Next Chapter

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.