i’m supposed to write a formula for the sum of squares using the given function and its parameters (i am allowed to add variables) but i can’t seem to get it right. the formula i came up with only computes the summation of the two numbers (not squared). please help, thank you!
/* Suppose nLowerBound is -2 and nUpperBound is 4.
The function computes:
(-2)^2 + (-1)^2 + (0)^2 + (1)^2 + (2)^2 + (3)^2 + (4)^2 = 35
The function returns 35.
*/
int sumOfSquares(int nLowerBound,
int nUpperBound) {
// your code here
int nSum;
nSum = ( (nUpperBound * (nUpperBound + 1)) - (nLowerBound * (nLowerBound - 1)) ) / 2;
return nSum;
>Solution :
The simplest way to compute the sum is to use a loop:
int sumOfSquares(int nLowerBound,
int nUpperBound) {
// Initially set the sum as zero
int nSum = 0;
for (int i=nLowerBound; i<=nUpperBound; i++) {
// for each number between the bounds, add its square to the sum
nSum = nSum + i*i;
}
return nSum;
}