This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
If you want to devise a function to sum the values of an array, consider the below:
public int sumNum(int[] num) {
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
It doesn't make sense to return a double
for a function like this, but you still can. I changed it to int
since num
is always int
as per its declaration. I'm only making an assumption to what you really wanted.
Also consider taking num
as argument for the function, thereby giving it local scope within the function. You could keep it global but again, I'm making an assumption of what you really want. Plus, it allows for re-using this function if you ever wanted to find the sum of something else.
You also want some initial value for sum
: since you're summing the values in an array, I initialized sum
to 0
. Otherwise, when you do sum = sum + num[i]
, what exactly is sum
initially? You need some starting point.