Ques:-18) Write a program to generate all combinations of 1, 2 and 3 using for loop.

Here’s a C program that generates all combinations of the numbers 1, 2, and 3 using nested for loops:

				
					#include<stdio.h>
#include<conio.h>
void main()
{
  int i,j,k;
  clrscr();
  printf("Maximum combination are:\n");
  for(i=1;i<=3;i++)
  {
    for(j=1;j<=3;j++)
    {
      for(k=1;k<=3;k++)
      {
	 if(i!=j&&j!=k&&k!=i)
	 {
	   printf("%d,%d,%d\n",i,j,k);

	 }
      }
    }
  }
  getch();
}

				
			

Out Put

				
					1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
				
			

Another Example

				
					#include <stdio.h>

int main() {
    int i, j, k;

    printf("All combinations of 1, 2, and 3:\n");

    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;
}

				
			

Explanation:

  • The program uses three nested for loops.
  • The outer loop (i) runs from 1 to 3.
  • The middle loop (j) also runs from 1 to 3.
  • The inner loop (k) runs from 1 to 3.
  • Inside the innermost loop, it prints the current values of i, j, and k.

Output:

When you run this program, it will generate the following output:

				
					All combinations of 1, 2, and 3:
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

				
			

Each line represents one unique combination of the numbers 1, 2, and 3.

Scroll to Top