Turn Desktop View Off
You are here:   HomeC Programming (Theory)Control Structures in CC Program Sum of digits of number repeatedly to obtain a single-digit number
by Dinesh Thakur Category: Control Structures

The program segment given below determines the sum of digits of a given number repeatedly until a single digit number is obtained. For example, 5985 => 27 => 9, where symbol => indicates a digit sum operation. Thus, if digit sum exceeds 9, it is used as a number for subsequent digit sum operations.

This code uses a two-level nested do ... while loop. The inner do ... while loop is used to determine the sum of digits of number num. After the sum of digits is calculated in the inner do ... while loop, it is assigned to num as a new number. The outer do ... while loop determines the sum of digits repeatedly as long as num is greater than 9.

#include <stdio.h>

void main()

{    

       int num,sum; 

       clrscr();

       printf("Enter a Number :");

       scanf("%d",&num);

       do

       {

              sum = 0;      /* sum of digits of number */

              do

              {

                    sum += num % 10;    /* add LS digit to sum */

                    num /= 10;               /* remove LS digit from num */

              }    while (num > 0);

                    num = sum;             /* use digit sum as new number */

       }           while (num > 9);      /* as long as num has 2 or more digits */

                    printf("Sum of digits %d\n", sum);

                    getch();

}

        Sum of digits of number repeatedly to obtain a single-digit number



Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article