Thread: sum of n natural numbers

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    7

    sum of n natural numbers

    Hi,i cant figure out what is wrong this program.Pls help.

    Code:
    #include<stdio.h>
    int main()
    {
    int n,i,sum=0;
    printf("enter upper limit");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    sum=sum+i;
    printf("%d",sum);
    }
    return;
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Line 6... the user enters an upper limit... say 5
    line 7 ... a loop that counts from 0 to the upper limit -1 (0, 1, 2, 3, 4)
    line 9 ... the value of the loop counter is added to the variable sum. (sum + 0, sum + 1, sum + 2, sum + 3, sum + 4)
    line 10... prints the result accumulated in sum... (sum + 0 + 1 + 2 + 3 + 4 = 10)
    line 12... actually this line contains an error. it should be return 0; since an integer is promised at int main()

    Does that help?

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    7
    No,i still get garbage value:013610

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Quote Originally Posted by Monochrome View Post
    No,i still get garbage value:013610
    0 + 0 = 0
    0 + 1 = 1
    1 + 2 = 3
    3 + 3 = 6
    6 + 4 = 10

    They are NOT garbage values

    Tim S.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    7
    Damn never realised that.Thx man

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Monochrome View Post
    No,i still get garbage value:013610
    Take a close look at your printf() on line 10 ... it is printing the correct answers but all crunched togeter.

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    7
    Ok now i put newline character.Thx for your help.
    Code:
    #include<stdio.h>
    int main()
    {
    int n,i,sum=0;
    printf("enter upper limit");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    sum=sum+i;
    printf("%d\n",sum);
    }
    Last edited by Monochrome; 11-01-2011 at 09:17 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 08-15-2010, 05:59 PM
  2. C and Natural Language Processing
    By hilarius in forum C Programming
    Replies: 1
    Last Post: 11-25-2009, 01:20 AM
  3. Natural Mergesort
    By wuzzo87 in forum C Programming
    Replies: 31
    Last Post: 04-14-2007, 09:41 PM
  4. natural leg movement
    By DavidP in forum Game Programming
    Replies: 32
    Last Post: 01-11-2004, 09:01 AM
  5. Natural Merge Sort
    By penny_731729 in forum C Programming
    Replies: 1
    Last Post: 04-28-2003, 04:12 PM