Reputation: 55
I need to square the predefined array, but the problem is the iteration depends on what number the user enter is. I'm only new to java and do not know how it works.
int[] array = {1, 2, 3, 4, 5}; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
int sq = 0, sq2 = 0, sq3 = 0, sq4 = 0, sq5 = 0;
for (int i = 0; i < num; i++) {
sq = array[i] * array[i];
sq2 = array[i] * array[i];
sq3 = array[i] * array[i];
sq4 = array[i] * array[i];
sq5 = array[i] * array[i];
}
for (int i = 0; i < num; i++) {
System.out.println(sq);
System.out.println(sq2);
System.out.println(sq3);
System.out.println(sq4);
System.out.println(sq5);
}
Input:
1 //iteration
Output:
1
1
1
1
1
Expected output:
001
004
009
016
025
Upvotes: 1
Views: 195
Reputation:
You can use streams to square the elements of an array:
int[] array = {1, 2, 3, 4, 5};
// number of iterations
int i = 1;
// multiply each element of the array 'i' times
int[] squared = Arrays.stream(array)
.map(j -> IntStream.rangeClosed(0, i)
.map(k -> j)
.reduce(Math::multiplyExact)
.orElse(j))
.toArray();
// output
System.out.println(Arrays.toString(squared));
// [1, 4, 9, 16, 25]
See also: Returning a 2d array from inputed 1d array
Upvotes: 1
Reputation: 3027
to find the square of a number you can also use Math.pow()
,
num
which it's value will be entered by user may cause problem so you need also to check that the value of i
which is the index of array do not exceed from the arrays indexprintf
to format the number output with leading zero:int[] array = { 1, 2, 3, 4, 5 }; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
for (int i = 0; i < num && i < array.length; i++) {
System.out.printf("%03d\n", array[i] * array[i]);
}
Upvotes: 1
Reputation: 892
The value of i
is 0 in the beginning. So all the values are actually storing the square of the 0th element that is the first element in the array which means they are all storing the square of "1".
Your code should be somewhat like this:
int[] array = {1, 2, 3, 4, 5}; // Predefined array.
Scanner in = new Scanner(System.in);
int num = in.nextInt(); // Number of loop.
int[] sq = {0, 0, 0, 0, 0};
for(int i = 0; i < num; i++)
{
for(int j = 0; j < 5; j++)
{
sq[j] = array[j] * array[j];
}
}
for(int i = 0; i < 5; i++)
{
System.out.println(sq[i]);
}
This should do the job.
Upvotes: 3