rosa
rosa

Reputation: 55

Nested loops to find counting numbers

never thought i had issues with nested loops well here Iam: What i want to achieve is this: Given two number A and B i need to find all counting numbers between 1 and the A*B for example A=4 B=3 i need this:

      1 2 3
      4 5 6
      7 8 9
      10 11 12

I wrote the initial parts but i can't figure out how can i write down the value which changes in every row

      for(int i=1; i<=A; i++){
                 for(int j=1; j<=B; j++){
                      System.out.println("?");}}

Having A*B gives me

    1 2 3
    2 4 6
    3 6 9
    4 8 12

I tried some other combinations too but to no luck, It might look straight forward but its the first time i'm facing this. Thanks in advance!

Upvotes: 2

Views: 3214

Answers (6)

Serith
Serith

Reputation: 241

The solution is ridiculously simply, just use one more variable and count it from 1 to A*B.

q = 0;
for(int i=0; i<A; i++){
    for(int j=0; j<B; j++){
        q++;
        System.out.print(q + " ");
    }
    System.out.println();
}

Upvotes: 1

Sam DeHaan
Sam DeHaan

Reputation: 10325

for(int i=0; i<A; i++){
    for(int j=0; j<B; j++){
        System.out.print(B*i + (j + 1));
    }
    System.out.println("");
}

Upvotes: 5

titus
titus

Reputation: 5784

for(int i=1;i<=A*B;i++)
{  System.out.printf("%d%c",i,(i%B!=0?' ':'\n'));
}

for(i=1;i<A*B;i+=B)
{ for(j=i;j<i+B;j++)
  { System.out.printf("%d ",j);
  }
  System.out.println();
}

Upvotes: 2

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

 for(int i=1; i<=A; i++){
                 for(int j=1; j<=B; j++){
                      System.out.print(B*(i - 1) + j);
                 }
                 System.out.println();
 }

Upvotes: 1

StanleyZ
StanleyZ

Reputation: 607

I don't know Why it has to be a nested loop? however, this one might work

for(int i=0; i < A; i++){
      for(int j=i*B; j<(i+1)*B; j++){
           System.out.print(j+1);
      }
      System.out.print("\n");
}

Upvotes: 2

K Mehta
K Mehta

Reputation: 10553

You can try (i-1)*B + j.

Another option is to just use 1 for loop:

int limit = A * B;
for (int i = 1; i <= limit; i++) {
    System.out.print(i + " ");
    if (i % B == 0) {
        System.out.println();
    }
}

Upvotes: 3

Related Questions