Skip to content
Advertisement

I am trying to add two float arrays into a third array but receive only zeros

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:

JavaScript

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.

JavaScript

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

JavaScript

The values j and i are not what you need them to be.

Change the above line in:

JavaScript

EDIT: as @SagunDevkota already stated, in your second loop,

change:

JavaScript

to

JavaScript

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:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement