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

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

 
				
					public class Combinations {

    public static void main(String[] args) {
        System.out.println("All combinations of 1, 2, and 3:");

        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                for (int k = 1; k <= 3; k++) {
                    System.out.println(i + " " + j + " " + k);
                }
            }
        }
    }
}

				
			

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