Reputation: 109
I'm supposed to write a program that asks for the number of rows the user wants. For example is the user entered 5 it will display all numbers from 25 to 1 arranged in 5 columns and 5 rows. Something like this should be the output if 5 is entered:
25 24 23 22 21
16 17 18 19 20
15 14 13 12 11
6 7 8 9 10
5 4 3 2 1
As you can see there is a pattern. the first number to appear is the square of the number. then the next number is number squared minus 1. Until it reached 21, 5 will be subtracted bringing 16. Then it will add by 1 until it reach 20. As you can see it is like a snake.
The problem is it works for any number EXCEPT when 1 is entered. 0 is the current result when 1 is entered.
Here's my current codes: please help me thanks
import java.util.*;
public class ArrayOutput2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number = 0;
System.out.print("Enter number of rows: ");
number = input.nextInt();
int[][] num = new int[number][number];
int k=1, i, j;
while(k< (number*number))
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}
for(i=0;i<number;i++)
{
for(j=0;j<number;j++)
System.out.print(num[i][j]+"\t");
System.out.println();
}
}
}
Upvotes: 0
Views: 172
Reputation: 12363
when number = 1
, the 2D array int[][] num
does not get populated as it does not enter the loop while(k<(1*1))
, hence bottom for loop which prints the 2D values prints only 0
because array itself does not get initialized.
Upvotes: 1
Reputation: 1341
Suppose that the user inputs 1
as a value, therefore number == 1
.
You allocate an array num[1][1], that is an array with only one possible cell, number[0][0]
Then the loop is initiated
k=1;
while (k<(number*number)); // which is like while(1<1*1)==FALSE
therefore the loop is never used. You can use:
1) Either a do-while
loop to run the loop at least once
2) or add an if
statement just after while()
loop ends:
// Using an IF statement immediately after the unmodified while()
if (number==1)
{
num[0][0]=1;
}
// or with a loop DO-WHILE
do
{
for(i=number; i>=1; i--)
{
if (i%2==1)
{
for(j=number-1; j>=0; j--)
{
num[i-1][j]=k;
k++;
}
}
else
for(j=0; j<=number-1; j++)
{
num[i-1][j]=k;
k++;
}
}
}while(k<(number*number));
Upvotes: 2
Reputation: 11050
num[0][0]
has not been initialized since you didn't enter the loop. Try this before the loop:
if (number == 1)
num[0][0] = 1;
Upvotes: 0