Digital जीवन

Free Online Education for India...

Full width home advertisement

Computer Basic

C Programming

Engineering Graphics

Post Page Advertisement [Top]

Dr. A.P.J. Abdul Kalam Technical University, Lucknow

KCS151 / KCS251 Programming for Problem Solving - Using C Language


Lab Exercises


21. Write a program to find the sum of digits of a 5 digit number using recursion.


/*
 File: Prgrm21.c
 Author: Aditya Saini
 Date: Jan 17, 2021
 Description: Program to find the sum of digits of a 5 digit number using recursion.
*/

#include <stdio.h>

int sum_of_digits (int);

int main (void)
{
     int num;
     int sum;

     //Input number
     printf ("Input number: ");
     scanf ("%d", &num);

     //Fucntion call
     sum = sum_of_digits (num);

     //Print result
     printf ("Sum of digits: %d", sum);

     return 0;
};

int sum_of_digits (int num)
{
     //Calculate sum of digits
     //Base case
     if (num <= 9)
          return num;
     else
          //Recursive call
          return num % 10 + sum_of_digits (num / 10);
};

Output

Input number: 12345
Sum of digits: 15



No comments:

Post a Comment

Please do not post spam links.

Bottom Ad [Post Page]

| Designed by Colorlib