CodeBlanks Logo Icon CodeBlanks

Summary - Loops

Combine for, while and nested loops to write a multiplication table.

Summary - Loops

In this section you learned for, while, do-while, break, continue and nested loops. Now we'll combine them in a multiplication table app.

The multiplication table is the classic example of nested loops: the outer loop produces rows, the inner produces columns. Then we'll add a while menu loop.

Practice 3x3 multiplication table

Write a C program. Write an outer for (int i = 1; i <= 3; i++) and inner for (int j = 1; j <= 3; j++) loop. In the inner loop print printf("%d ", i * j);. At the end of the outer print printf("\n");. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Print a 3x3 multiplication table with nested for
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            printf("%d ", i * j);
        }
        printf("\n");
    }
    return 0;
}

Expected output

1 2 3 
2 4 6 
3 6 9

Practice 1 to 5 with while

Write a C program. Declare int i = 1;. Use a while (i <= 5) loop to print printf("%d\n", i); and increment with i++;. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare i, print 1 to 5 with while
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int i = 1;
    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}

Expected output

1
2
3
4
5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which loop builds a multiplication table?

main.c
for (i=1; i<=n; i++)
  for (j=1; j<=n; j++)
    printf("%d ", i*j);
  • Single while
  • Switch
  • Single do-while
  • Nested for Correct answer

Explanation: The multiplication table uses nested for loops.

2 End the do-while

Question
do {
    scanf("%d", &choice);
} ____ (choice == 1);
Answer
do {
    scanf("%d", &choice);
} while (choice == 1);

Explanation: do-while ends with while and a semicolon.

3 Match loop and control

Term Meaning
for Counted
while Conditional
do-while At least once
break Exit

All lessons in Beginner