944,153 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 8618
  • C RSS
Sep 27th, 2004
0

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

Expand Post »
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.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Ginger is offline Offline
2 posts
since Sep 2004
Sep 27th, 2004
0

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

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. }
Reputation Points: 17
Solved Threads: 9
Posting Whiz in Training
frrossk is offline Offline
220 posts
since Sep 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: how to place a specific info from input file
Next Thread in C Forum Timeline: A puzzl about function





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC