user391967 - 9 months ago 43

C Question

I can't get the codes right.

Can somebody help?

`#include<stdio.h>`

int main()

{

int n, sum,i,j;

printf("Please enter an integer, n = ");

scanf("%d", &n);

for(i=1;i<=n;i++)

for(j=1;j<=i;j++)

sum = sum + n;

printf("sum = %d", sum);

return 0;

}

Answer

- You are not initialising
`sum`

. Initialise it with`0`

. - You shouldn't be adding
`n`

at each step, but`j`

.

Of course, this is to fix your current code. There are better approaches to solving the problem, which others have already mentioned.

**Edit**:

Just for fun, here's a formula that allows you to solve the problem in `O(1)`

:

Your sum is equal to `n*(n + 1)*(2*n + 1) / 12 + n*(n + 1) / 4`

.

This is obtained by writing it as a sum and using the fact that the sum of the first `n`

consecutive squares is `n(n + 1)(2n + 1) / 6`

and the sum of the first `n`

positive ints is `n(n + 1)/2`

. +1 if you can find a nicer form of the formula.