Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested while loop in java not working

Tags:

java

user input

5

Required output (using while loop)

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Code:

while (temp1 <= a) {
    while (temp2 <= a) {
        temp = temp2 * temp1;
        System.out.print(temp + " ");
        temp2++;
    }
    temp1++;
    System.out.println();
}

i am taking a as input and try to form that figure but i can't.. please help

like image 444
Arka Bhattacharjee Avatar asked Nov 24 '25 02:11

Arka Bhattacharjee


2 Answers

Value of temp2 after inner while loop will be a+1. Since you not resetting it to 1 later you will not enter this inner loop again because condition while(temp2<=a) will not be fulfilled. To correct it set temp2 to 1 inside outer loop, before or after inner loop.

like image 61
Pshemo Avatar answered Nov 26 '25 18:11

Pshemo


If I have to break down the problem into simple words,

  • The user will input a number: "x".
  • Create a 2D matrix of the size arr[x][x]
  • the value of each element will be a[i][j] = i * j; // considering (i=1; i<=x) & (j=1;j<=x)
  • Print out the matrix.

There are n number of ways you can do it.

I guess using for loops would be the simplest.

like image 26
ajc Avatar answered Nov 26 '25 17:11

ajc