I want to use 3 looping structures for three different arrays. The first loop generates numbers 0 to 49. The second loop takes the first loop numbers and squares them. The third loop holds the sum of all 49 values.
If I put it all in a single statement, I get exactly what I want, except it doesn’t fill each array:
System.out.println(value[i] + "t" + Math.pow(value[i], 2) + "t" + (value[i] + Math.pow(value[i], 2)));
I’m having troubles with the code. After using print statements, I can see the first loop working, however it isn’t filling the second loop which is resulting in all zeros.
int loopMax = 49; value = new float [50]; valueSQ = new float [50]; sum = new float [value.length + valueSQ.length]; for (i = 0; i < loopMax; i++) { value[i] = i + 1; } /*Results in 49 zeros*/ for (j = 0; j < loopMax; j++) { valueSQ[j] = (float) Math.pow(value[i], 2); //System.out.println (valueSQ[j]); } /*Results in all zeros*/ for (k = 0; k < loopMax; k++) { sum[k] = valueSQ[j] + value[i]; System.out.println (sum[k]); }
This is my base code. I figured the zeros were because I wasn’t filling the second array properly. I tried creating new arrays since I can’t change the old arrays but it hasn’t helped. Could someone explain to me what I am doing wrong or why I’m getting all zeros after the first loop?
Advertisement
Answer
sum[k] = valueSQ[j] + value[i];
The values j and i are not what you need them to be.
Change the above line in:
sum[k] = valueSQ[k] + value[k];
EDIT: as @SagunDevkota already stated, in your second loop,
change:
valueSQ[j] = (float) Math.pow(value[i], 2);
to
valueSQ[j] = (float) Math.pow(value[j], 2);
The reason for this is because i is not reset for the second loop, nor will it augment, the way j will.
You should consider i to be out of scope for the second and third loop, and j for the third loop.
As @JonSkeet remarked, it is better to declare the variable where you need them in such cases:
for (i = 0; i < loopMax; i++) { value[i] = i + 1; } for (j = 0; j < loopMax; j++){ valueSQ[j] = (float) Math.pow(value[i], 2); }
This shows us that both i and j are declared as instance variables, static variables, or earlier in the method this code is from.
If you remove those variables, and re-write the code like this:
for (int i = 0; i < loopMax; i++) { value[i] = i + 1; } for (int j = 0; j < loopMax; j++){ valueSQ[j] = (float) Math.pow(value[i], 2); }
When you try to compile this, the compiler will tell you that you are using i out of it’s scope. The variable i only exists within the scope of the first loop, so the code for the second loop would not compile.