Given the jagged Array, we are asked to use a looping statement to display the character based on the position. Display a "*" if the position matched or a " " if it doesn't.
int arr [][] = {{0,4,8,12,13,14,15,18,19,20,21,24,28},
{0,4,7,9,12,16,18,22,25,27},
{0,1,2,3,4,6,10,12,16,18,22,26},
{0,4,6,10,12,13,14,15,18,19,20,21,26},
{0,4,6,7,8,9,10,12,18,26},
{0,4,6,10,12,18,26}};
I have created a program, but the output is not what I expected and I am now stuck.
for (int i = 0; i < arr.length; i )
{
for (int j = 0; j < arr[i].length - 1; j )
{
for (int spaces = 1; spaces < arr[i][j 1]-arr[i][j]; spaces )
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
}
The output was suppose to be Happy but I get: enter image description here
CodePudding user response:
It's because of your program does not compare the first j
value (which is 0) with itself. Since every value equals itself you can add manually *
for each line like this.
int arr [][] = {{0,4,8,12,13,14,15,18,19,20,21,24,28},
{0,4,7,9,12,16,18,22,25,27},
{0,1,2,3,4,6,10,12,16,18,22,26},
{0,4,6,10,12,13,14,15,18,19,20,21,26},
{0,4,6,7,8,9,10,12,18,26},
{0,4,6,10,12,18,26}};
for (int i = 0; i < arr.length; i )
{
System.out.print("*");
for (int j = 0; j < arr[i].length - 1; j )
{
for (int spaces = 1; spaces < arr[i][j 1]-arr[i][j]; spaces )
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
}
CodePudding user response:
Try this.
for (int i = 0; i < arr.length; i ) {
for (int j = 0, p = -1; j < arr[i].length; p = arr[i][j ])
System.out.print(" ".repeat(arr[i][j] - p - 1) "*");
System.out.println();
}
output:
* * * **** **** * *
* * * * * * * * * *
***** * * * * * * *
* * * * **** **** *
* * ***** * * *
* * * * * * *