I am to write a program to read a non-negative integer n and call function add_it() to calculate the sum ... If n is 5, the sum 1+2+3... would be computed. n must be less than 8943923. Use a for loop, rather than the summation formula. I am to put main() and add_it() in the same file by calling add_it(). The following is what I have come up with, but I am getting the wrong answer main() {

int main()    {
    int n,sum;  {

    printf("Enter a non_negative number to sum:\n");
    scanf("%d", &n);

int add_it()   {

    int n,sum;   {
    n<8943923;
    for  (n=0;
          n<8943923;
          n*(n+1)/2) {
    printf("%d\n",n);
    sum=n*(n+1)/2;
    if (n<8943923) break;
}}}
    printf("The summation of %d is %d\n",n,sum);

return(sum);

}}

When I execute the program I get the following:

Enter a non-negative number to sum: (I enter say 20)
The summation of 20 is 4.

This is what I want except the answer should not be 4.

Can anyone help me figure out where I went wrong in this for loop and my equation for getting the sum? Thank you to all who may respond.

Maybe this will work:

#include <stdio.h>
#include <stdlib.h>

int add_it(int n);

int main() 
{
int n,sum;

printf("Enter a non_negative number to sum:\t");
scanf("%d", &n);
if (n >= 8943923) printf ("n too big\n");
else
{
sum = add_it (n);
printf("The summation of %d is %d\n",n,sum);
}
system ("PAUSE");
}

int add_it(int n) 
{
int sum=0, i;
for (i=1; i<=n; i++)
{
printf("%d\n", i);
sum+=i;
}
return sum;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.