Using a for loop to sum an integer n and call function add_it

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Sep 2004
Posts: 2
Reputation: Ginger is an unknown quantity at this point 
Solved Threads: 0
Ginger Ginger is offline Offline
Newbie Poster

Using a for loop to sum an integer n and call function add_it

 
0
  #1
Sep 27th, 2004
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.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 220
Reputation: frrossk is an unknown quantity at this point 
Solved Threads: 9
frrossk's Avatar
frrossk frrossk is offline Offline
Posting Whiz in Training

Re: Using a for loop to sum an integer n and call function add_it

 
0
  #2
Sep 27th, 2004
Maybe this will work:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int add_it(int n);
  5.  
  6. int main()
  7. {
  8. int n,sum;
  9.  
  10. printf("Enter a non_negative number to sum:\t");
  11. scanf("%d", &n);
  12. if (n >= 8943923) printf ("n too big\n");
  13. else
  14. {
  15. sum = add_it (n);
  16. printf("The summation of %d is %d\n",n,sum);
  17. }
  18. system ("PAUSE");
  19. }
  20.  
  21. int add_it(int n)
  22. {
  23. int sum=0, i;
  24. for (i=1; i<=n; i++)
  25. {
  26. printf("%d\n", i);
  27. sum+=i;
  28. }
  29. return sum;
  30. }
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC