Write a c program to generate all combinations of 1, 2 and 3 using for loop.

April 28, 2023 · Team EasyExamNotes · 1 min read (est.) · 0 comments

Share on WhatsApp

Here’s a C program that uses nested for loops to generate all combinations of 1, 2, and 3:

C
#include <stdio.h>

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

Output:

1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3

In this program, we use three nested for loops, with each loop iterating over the numbers 1, 2, and 3. Inside the innermost loop, we print out the current combination of numbers using printf(). This generates all possible combinations of the numbers 1, 2, and 3.

Discussion

Ask a question, share your thoughts or report an error.

Sign in to participate in the discussion.

Join the discussion