Given two numbers n1 and n2 such that n2>n1, find sum of squares of all numbers from n1 to n2 (including n1 and n2).
My Approach:
I tried to solve the problem using a for loop iterated from n1
to n2
but I am getting wrong answer
Below is my function for the code:
public int computeSumofSquares (int n1, int n2)
{
int sum=0;
if(n2>n1)
{
for(int i=n1;i<=n2;i++)
{
sum=((sum)+(n1*n1));
}
}
return sum;
//write your code here
}
For the Input
Parameters Actual Output Expected Output
'8' '10' 192 245
You are squaring n1
on every iteration. Instead you should square i
. As a short form of sum=((sum)+(i*i));
you can write sum += i * i;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With