Why is my function not returning the sum of "n" integers?

Viewed 50

I have a function that is supposed to return the sum of the first "n" integer squares. So with the argument n being 4, it is supposed to return the sum of the first 4 square integers which would be 30 because 1^2 + 2^2 + 3^2 + 4^2 = 30. The problem is is my function returns 5 for some reason. What is the problem with my code?

#include <iostream>

using namespace std;

int sum_of_squares(int n) {

    int sum = 0;

    for (int i = 0; i <= n; i++) {
        i *= i;
        sum += i;
    }

    return sum;

}

int main() {

    cout << sum_of_squares(4) << endl;

}
2 Answers

The code does not do what you have described. You have weirdly overcomplicated it:

for (int i = 1; i <= n; i++) 
{
    sum += i * i;
}

In your original loop are modifying the loop control variable, so the loop terminated on the third iteration (which should be the second because summing 0 * 0 has no effect).

                    sum
----------------------------
0    i = 0 * 0       0
1    i = 1 * 1       1
2    i = 2 * 2       5 - loop terminates i == 4

I recommend you get into the habit of using a debugger to solve these kind of semantic problems. In this case would be clear what is happening when you step through the loop one iteration at a time and observe the effect on the variables.

    #include <iostream>
    
    using namespace std;
    
    int sum_of_squares(int n) {
    
        int sum = 0;
    
        for (int i = 0; i <= n; i++) {
            sum+=(i*i)   ;
              
        }
    
        return sum;
    
    }
    
    int main() {
    
        cout << sum_of_squares(4) << endl;
    
    }
Related