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;
}
sum. Initialise it with0.nat each step, butj.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
nconsecutive squares isn(n + 1)(2n + 1) / 6and the sum of the firstnpositive ints isn(n + 1)/2. +1 if you can find a nicer form of the formula.