C Program To Calculate Sum of Digits Using Recursion

A 5-digit positive integer is entered through the keyboard, write a recursive and a non-recursive function to calculate sum of digits of the 5-digit number.

Analyze The Problem Statement

1. User enters a 5-digit number.
2. We need to write 2 functions to calculate sum of digits of user entered number.
3. One function should use recursive logic and the other should calculate sum of digits without using recursion.

Related Read:
Recursive Functions In C Programming Language
Calculate Sum of Digits: C Program

Video Tutorial: C Program To Calculate Sum of Digits Using Recursion


[youtube https://www.youtube.com/watch?v=tPbkgtSoG4Y]

YouTube Link: https://www.youtube.com/watch?v=tPbkgtSoG4Y [Watch the Video In Full Screen.]


Source Code: C Program To Calculate Sum of Digits Using Recursion

#include<stdio.h>

int add(int);
int add_rec(int);

int main()
{
    int num;

    printf("Enter a 5-digit positive integer number\n");
    scanf("%d", &num);

    printf("Sum of Digits(without using recursion): %d\n", add(num));
    printf("Sum of Digits(using recursion): %d\n", add_rec(num));

    return 0;
}

int add(int num)
{
    int sum = 0;

    while(num)
    {
        sum = sum + (num % 10);
        num = num / 10;
    }

    return(sum);
}

int add_rec(int num)
{
    if(num)
        return( (num % 10) + add_rec(num / 10) );
    else
        return 0;
}

Output 1:
Enter a 5-digit positive integer number
12345
Sum of Digits(without using recursion): 15
Sum of Digits(using recursion): 15

Output 2:
Enter a 5-digit positive integer number
15937
Sum of Digits(without using recursion): 25
Sum of Digits(using recursion): 25

Logic To Calculate Sum of Digits without using Recursion

1. Using (num % 10), we fetch the last digit of the user entered number and add it to the previous value of sum.
2. Next we reduce the uer entered number by 1 digit(from the right end) by dividing the number by 10 i.e., num / 10.
3. We put above two steps/logic into while loop. We iterate through the while loop until num is positive. Once num value is 0, control exits the while loop.
4. Outside while loop we return the value present in variable sum – which will have the sum of all the individual digits of the user entered number.
If num = 12345;

numnum%10sumnum/10
12345551234
123449123
12331212
122141
11150

If you observe above table, when num becomes 0, sum has 15 in it. So 15 is the sum of all the individual digits of the user entered number 12345.

i.e., 1 + 2 + 3 + 4 + 5 = 15.

Full logic with separate video explaining this concept is present at Calculate Sum of Digits: C Program. Kindly watch it without fail.

Logic To Calculate Sum of Digits using Recursion

If num is positive we execute below line of code

return( (num % 10) + add_rec(num / 10) );

If num is 0, then we return zero.

Recursive Function Calls – Stacking of calls

Call Fromnum % 10add_rec(num / 10)
add_rec(12345)5add_rec(1234)
add_rec(1234)4add_rec(123)
add_rec(123)3add_rec(12)
add_rec(12)2add_rec(1)
add_rec(1)1add_rec(0)

Value Returning – Control Shifting back.

Return To(num % 10) + resultReturn value
add_rec(0)return(0)0
add_rec(1)1 + add_rec(0)1 + 0 = 1
add_rec(12)2 + add_rec(1)2 + 1 = 3
add_rec(123)3 + add_rec(12)3 + 3 = 6
add_rec(1234)4 + add_rec(123)4 + 6 = 10
add_rec(12345)5 + add_rec(1234)5 + 10 = 15

So at the end 15 is returned back to main() method and the result is printed on the console window.

Note: Whenever there is a call to a function, the function instance(and memory associated with it) gets stored in the memory stack. Once the function returns value to calling function, the control shifts back to the calling function and the memory instance gets popped out of the memory stack immediately after returning the value.

Ternary or Conditional Operator And Recursion

int add_rec(int num)  
{  
    return( ( num > 0 ) ? ( (num % 10) + add_rec(num / 10) ) :  0 );

}  

You can even write the recursive logic to find sum of digits of a number using above ternary or conditional operator.

Source Code: C Program To Calculate Sum of Digits Using Recursion And Ternary Operator

#include<stdio.h>

int add(int);
int add_rec(int);

int main()
{
    int num;

    printf("Enter a 5-digit positive integer number\n");
    scanf("%d", &num);

    printf("Sum of Digits(without using recursion): %d\n", add(num));
    printf("Sum of Digits(using recursion): %d\n", add_rec(num));

    return 0;
}

int add(int num)
{
    int sum = 0;

    while(num)
    {
        sum = sum + (num % 10);
        num = num / 10;
    }

    return(sum);
}

int add_rec(int num)
{
    return( ( num > 0 ) ? ( (num % 10) + add_rec(num / 10) ) :  0 );
}

Output 1:
Enter a 5-digit positive integer number
12345
Sum of Digits(without using recursion): 15
Sum of Digits(using recursion): 15

Output 2:
Enter a 5-digit positive integer number
98654
Sum of Digits(without using recursion): 32
Sum of Digits(using recursion): 32

You can know more about Ternary or Conditional Operators in this video tutorial Ternary Operator / Conditional Operator In C.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Calculate Sum of Digits: C Program

Lets ask the user to input a integer number through keyboard. Lets write a c program to calculate sum of its digits.

Related Read:
Find Sum of Digits In A Given Number: C

Note: We assign variable sum = 0 to avoid garbage values in sum.

If user enters 456, we apply the modulo division to get the individual values.
Ex:
456 % 10 = 6
45 % 10 = 5
4 % 10 = 4

We get 456, 45 and 4 by dividing the original value by 10.
Ex:
456 user entered value.
456 / 10 = 45
45 / 10 = 4

Now the sum.

sum = sum + rem;

06 = 0 + 6
11 = 6 + 5
15 = 11 + 4

So the sum of digits in the given integer number is 15.

Calculate Sum of Digits: C Program


[youtube https://www.youtube.com/watch?v=CdHLY5S2Xdc]

YouTube Link: https://www.youtube.com/watch?v=CdHLY5S2Xdc [Watch the Video In Full Screen.]


Source Code: Calculate Sum of Digits: C Program

#include < stdio.h >

int main()
{
    int num, reminder, sum = 0;

    printf("Enter a integer number\n");
    scanf("%d", &num);

    while(num != 0)
    {
     reminder = num % 10;
     sum      = sum + reminder;
     num      = num / 10;
    }

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

    return 0;
}

Output 1:
Enter a integer number
456
Sum of digit is 15

Output 2:
Enter a integer number
8910
Sum of digit is 18

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Find Sum of Digits In A Given Number: C

Video Tutorial to illustrate, C Program to find sum of digits in the given/user entered integer number.

In this program we assign variable sum = 0 to avoid garbage values in sum before the calculation, which would result in wrong output.
We store the user entered value in num.

1
2
3
4
5
6
 while( num )
  {
    rem = num % 10;
    sum = sum + rem;
    num = num / 10;
  }

Here the loop executes until the value of num is zero.

If user enters 123, we apply the modulus to get the individual values.
Ex:
123 % 10 = 3
12 % 10 = 2
1 % 10 = 1

We get 123, 12 and 1 by dividing the original value by 10.
Ex:
123 user entered value.
123 / 10 = 12
12 / 10 = 1

Now the sum.

sum = sum + rem;

3 = 0 + 3
5 = 3 + 2
6 = 5 + 1

So the sum of digits in the given integer number is 6.

Video Tutorial: Find Sum of Digits In A Given Number: C


[youtube https://www.youtube.com/watch?v=UnXfCTtHNWw]

YouTube Link: https://www.youtube.com/watch?v=UnXfCTtHNWw [Watch the Video In Full Screen.]



Full Free Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include < stdio.h >
#include < conio.h >
 
void main()
{
int num, rem, sum = 0;
clrscr();
 
printf("Enter an integer number\n");
scanf("%d", &num);
 
while(num)
{
  rem = num % 10;
  sum = sum + rem;
  num = num / 10;
}
 
printf("\nThe sum of digits is %d", sum);
getch();
}

Output:
Enter an integer number
123
The sum of digits is 6