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 variablesint num, sum ;// Initialize variablesnum = 327;// Call function and display the valuesum = rsum ( num ) ;printf ( "Sum of digits = %d\n", sum ) ;return 0 ;}int rsum ( int n ){// Declare variablesint s, d ;while ( n != 0 ){// Store the right-most digitd = n % 10 ;// Remove the right-most digitn = n / 10 ;// Add the digit value in the rest of the sums = s+ d ;}// Return sum to the calling pointreturn ( 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.