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
开发者_如何学Go 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!
for(int i=0; i<A; i++){
for(int j=0; j<B; j++){
System.out.print(B*i + (j + 1));
}
System.out.println("");
}
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();
}
}
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");
}
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();
}
for(int i=1; i<=A; i++){
for(int j=1; j<=B; j++){
System.out.print(B*(i - 1) + j);
}
System.out.println();
}
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();
}
精彩评论