user391967 user391967 - 1 year ago 96
C Question

write program to perform sum = 1+ (1+2) + (1+2+3) + ... + (1+2...+n)

I can't get the codes right.
Can somebody help?

int main()
int n, sum,i,j;

printf("Please enter an integer, n = ");
scanf("%d", &n);

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

return 0;

Answer Source
  1. You are not initialising sum. Initialise it with 0.
  2. 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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download