In this article, we will learnn how to find sum of digits of a number using Recursion.
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily.
Need of Recursion
Recursion is an amazing technique with the help of which we can reduce the length of our code and make it easier to read and write. It has certain advantages over the iteration technique which will be discussed later. A task that can be defined with its similar subtask, recursion is one of the best solutions for it.
For example; The Factorial of a number using recursion.
Find sum of digits of a number using Recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/* * C# Program to Find Sum of Digits of a Number using Recursion */ using System; class program { public static void Main() { int num, result; pro pg = new pro(); Console.WriteLine("Enter the Number : "); num=int.Parse(Console.ReadLine()); result =pg.sum(num); Console.WriteLine("Sum of Digits in {0} is {1}", num, result); Console.ReadLine(); } } class pro { public int sum(int num) { if (num != 0) { return (num % 10 + sum(num / 10)); } else { return 0; } } } |