Thread: program review

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    34

    program review

    hi
    is there any better method for finding sum of three numbers??
    Code:
    #include<stdio.h>
    main()
    {
    int a,s;
    printf("enter a number");
    scanf("%d",&a);
    for( ;a!=0;)
    {
    s=s+(a%10);
    a=a/10;
    }
    printf("the sum is%d",s);
    getch();
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    You mean the sum of the digits? No, not really. Since this code won't work properly with negative numbers, you should make a and s an unsigned int (use %u instead of %d). You should also write "int main()" instead of "main()" since C99 will require explicit return types. You could also write "s += a%10;" and "a /= 10;".

    Edit: Better yet, "int main(void)". You could also replace "for( ;a!=0;)" with the clearer "while (a != 0)" or just "while (a)".
    Last edited by robatino; 08-16-2007 at 11:03 AM.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by shuaib.akram View Post
    hi
    is there any better method for finding sum of three numbers??
    Since you are processing the number digit-by-digit anyway, there's no much point in converting it to a real integer at all:

    Code:
    int main()
    {
        char number[16], *ptr;
        int sum = 0;
    
        scanf("&#37;15s", number);
        for(ptr = number; *ptr; ptr++)
        {
            sum += *ptr - '0';
        }
        printf("The sum is %d", sum);
        return 0;
    }

  4. #4
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    No, that's not the best way.

    Try learning some math, like some "Sum of" algorithms.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  2. BOOKKEEPING PROGRAM, need help!
    By yabud in forum C Programming
    Replies: 3
    Last Post: 11-16-2006, 11:17 PM
  3. Can someome help me with a program please?
    By WinterInChicago in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2006, 10:58 PM
  4. review my telephone network simulation program
    By debuger2004 in forum C Programming
    Replies: 3
    Last Post: 06-20-2003, 01:26 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM