felipe342 felipe342 - 17 days ago 5
Java Question

Creating a class that squares and sums an array?

I'm trying to write a class method that squares, then sums an array but I've no clue how to advance from here. I also don't know if I should split the method to square it and then another to sum it or if i can actually combine them into this one. Here's what I've come up with so far...though its not much.

public int sqSum(){
int squm = 0;
for(int i=0; i<array.length; i++) {
sqSum += array[i] * array[i];
}
return sqSum;
}


Thanks for the help everyone. Looking at it now it seems extremely simple, guess I was too frustrated to take a good look at it.

Answer

The problem is you are actually declaring the same sqSum variable again and again without summing.

So declare it outside the for loop as shown below:

public int sqSum(){
    int sqSum =0;//declare it outside loop and use the same

    for(int i=0; i<array.length; i++)
       sqSum = sqSum + array[i] * array[i]; //add each product to previous sqSum

    return sqSum;
}