Thread: Sum till a Single Digit

  1. #1
    Registered User
    Join Date
    Jan 2020
    Posts
    8

    Sum till a Single Digit

    Q) Write a program that accepts integer as input and repeatedly sums it digits till it reaches single digit. It the outputs that single digit.
    Code:
    #include<stdio.h>
    int main()
    {
       int num,r,sum=0;
       printf("Enter a no.");
       scanf("%d",&num);
        do{
            while(num!=0){
            r=num%10;
            num/=10;
            sum +=r;
                }
            if(sum >9){
                num=sum;
                sum=0;
                }
          }while(num!=0);
        printf("the sum of digits is %d",sum);
    }
    I would like to know whether this is optimum or some better program can be written.(I haven't been taught functions yet).
    Thanks for constructive remarks.

  2. #2
    null pointer Structure's Avatar
    Join Date
    May 2019
    Posts
    338
    Mathematically speaking, it's pretty awesome. I would consider a recursive function only you wrote that you have not learned functions yet, so...


    whether this is optimum or some better program can be written.
    perhaps...
    Code:
    #include <stdio.h>
    
    int main() {
        int num, r, sum=0;
        printf("Enter a no: ");
        scanf("%d",&num);
        while( num != 0 ) {
            r = num % 10;
            num /= 10;
            sum += r;
            if ((num == 0) && (sum > 9)) {
                num = sum;
                sum = 0;
            };
        };
        printf("the sum of digits is %d",sum);
        return 0;
    };
    Last edited by Structure; 01-27-2020 at 09:53 AM.
    "without goto we would be wtf'd"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to display single digit int as four digit C++ Programming
    By Sloganathan in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2012, 11:30 AM
  2. Replies: 6
    Last Post: 04-17-2010, 11:31 AM
  3. Replies: 13
    Last Post: 11-13-2009, 08:47 AM
  4. leading zero on single digit int
    By confuted in forum C++ Programming
    Replies: 2
    Last Post: 07-31-2003, 04:48 PM
  5. ANSI value of a single digit
    By Iamien in forum C++ Programming
    Replies: 6
    Last Post: 05-24-2003, 05:56 PM

Tags for this Thread