...

/

Find the Sum of Digits of the Whole Number

Find the Sum of Digits of the Whole Number

Find the sum of digits of the whole number with and without recursion.

The sum of digits of the whole number without recursion

The program given below obtains the sum of digits of any whole number.

Press + to interact
# include <stdio.h>
int rsum ( int ) ;
int main( )
{
// Declare variables
int num, sum ;
// Initialize variables
num = 327;
// Call function and display the value
sum = rsum ( num ) ;
printf ( "Sum of digits = %d\n", sum ) ;
return 0 ;
}
int rsum ( int n )
{
// Declare variables
int s, d ;
while ( n != 0 )
{
// Store the right-most digit
d = n % 10 ;
// Remove the right-most digit
n = n / 10 ;
// Add the digit value in the rest of the sum
s = s+ d ;
}
// Return sum to the calling point
return ( s ) ;
}

Line 22: To find the sum of digits of the whole number, we will keep dividing the number by 10 until the quotient is not equal to 0.

Line 25: Since the program has to work for any number, we are not committing to variables ...

Access this course and 1400+ top-rated courses and projects.