Aakarsh
Aakarsh

Reputation: 63

Counting combinations in Java?

I am aiming to build a program with counting combinations so it counts all products from 1 to 10 like this: (1x1, 1x2, ..., 1x10, 2x1, 2x2, ...., 2x10, 3x10, ...., 10x1, 10x2, ...., 10x10)

Repeats allowed.

I started but I cannot do this properly.

I have

public static void main(String [] args){

int x = 1; int y=1;

while(y<=10){
 System.out.println(x*y);
} //while loop closure

   } //public static void closure.

The problem is this only works for x=1, but doesnt go on. What can I do here?

Thank you!

Upvotes: 0

Views: 142

Answers (2)

roottraveller
roottraveller

Reputation: 8232

Your code need a little change

  • first Initialized variable y
  • you need 2 loop for that operation to happened
  • You also need to increment variable x

     public static void main(String [] args){
      int x = 1; int y=1;
    
     while(x<=10){
       while(y<=10){
          System.out.println(x+"X"+y+" ");
          ++y;
       }
     ++x;
     } //while loop closure
    } //public static void closure.
    

It will print as expected in your program.

Upvotes: 0

konsolas
konsolas

Reputation: 1091

Problems:

  • You don't initialize the variable y, so your program won't compile.
  • You never increment y, so you have an infinite loop
  • You don't increment x either.
  • Putting two variables next to each other won't make them multiply. You'll get a "cannot resolve symbol" error.

I would highly recommend you go through some Java tutorials so that you understand what you are doing. Here is the corrected code:

for(int x = 1; x <= 10; x++) {
    for(int y = 1; y <= 10; y++) {
        System.out.println(x * y);
    }
}

Upvotes: 1

Related Questions