for counter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Geekibz
    New Member
    • Jan 2008
    • 12

    for counter

    Wsp c people.code below's supposed to printout the sum of all integers less than and including the limit specified by user.Something' s missing or wrong_ I jus can't figure out what, pls help.

    #include<stdio. h>
    main ()

    {
    int limit,i,sum;
    printf("Input limit:");
    scanf("%d",&lim it);
    for(i=limit;i>0 ;i--)
    sum=sum+i;
    printf("%d\n",s um);
    }
  • Simonius
    New Member
    • Feb 2008
    • 47

    #2
    I'd change it to:

    Code:
    #include <stdio.h>
    
    int main(){
    int limit, i, sum=0;
    
    printf("Input limit: ");
    scanf("%d",&limit);
    
    for(i=0;i<=limit;i++)
              sum+=i;
    
    printf("\nResult: %d",sum);
    
    return 0;
    It's a good habit to initialise what you're going to use.

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      Yup. By not initializing, you make sum's initial value the same as whatever last used the block of memory it got allocated, which if you're incredibly lucky, might actually be zero. Most likely, though, it'll be some kind of garbage data. Always, always, always, initialize before you use.

      Comment

      • NorseMN
        New Member
        • Feb 2008
        • 4

        #4
        Just an FYI,
        You don't need a loop to do this.
        The sum of all positive integers from 1 through N is given by N * (N + 1) / 2.
        Of course, you probably already know this and are just practicing your coding.

        Comment

        • sicarie
          Recognized Expert Specialist
          • Nov 2006
          • 4677

          #5
          Laharl-

          Please check your Private Messages, which are accessible through the PMs link in the top right corner of the page.

          Thanks,

          sicarie

          Comment

          Working...