C Program

In this tutorial we have been given a number. we’ll be calculating the sum of its digits

Examples : 

Input : n = 787
Output : 22

Input : n = 43
Output : 7
Method 1

Most Simple algorithm to calculate sum of digits of a number

  1. Get the number
  2. Declare a number to store the sum and initialize it to 0
  3. get the unit digit of number with help of % operator by dividing it by 10 and add it to the sum
  4. Now divide the number by 10 to remove the current unit digit
  5. repeat the steps 3 and 4 until the number is 0
  6. print the sum.

That’s how simple it is. Lol

So below is the implementation of the above algorithm

#include <stdio.h>

int main()
{
	int getSum(int n)
	{ 
		int sum=0;
		while(n!=0)
		{
			
			sum=sum+n%10;
			n = n / 10;
		}
		return sum;
	}
	
	int n=123456;
	int Sum=getSum(n);
	printf("%d",Sum);
	return 0;
}

Output

21
Method 2

What if I tell you that you don’t have to write a long program like the first one. You can calculate the sum in just one line of program.

#include <stdio.h>

/* Function to get sum of digits */
int getSum(int n)
{
	int sum;

	/* Single line that calculates sum */
	for (sum = 0; n > 0; sum += n % 10, n /= 10)
		;

	return sum;
}

// Driver code
int main()
{
	int n = 687;
	printf(" %d ", getSum(n));
	return 0;
}
Method 3: Recursive Method
// C program to compute
// sum of digits in number.
#include <stdio.h>
using namespace std;
int sumDigits(int no)
{
	return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}

int main(void)
{
	printf("%d", sumDigits(687));
	return 0;
}

Output

21
Method 4: Using Tail Recursion

This problem can also be solved using Tail Recursion. Here is an approach to solving it.

1. Add another variable “Val” to the function and initialize it to ( val = 0 )

2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10. 

3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to a single digit. 

4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits

Below is the implementation of the algorithm

#include <stdio.h>

int main()
{
	int getSum(int n, int val)
	{ 
		if(n<10)
		{
			val=val+n;
			return val;
		}
		else
		return getSum(n / 10, (n % 10) + val);
	
	}
	
	int n=123456;
	int Sum=getSum(n,0);
	printf("%d",Sum);
	return 0;
}

For more C Programming related blogs Visit Us Geekycodes . Follow us on Instagram.

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com

Leave a Reply