# C Program for Sum of Digits of a Number

In c program for sum of digits of a number, we take the help of loops and traditional mathematical operations.

This post will deal with the c program for sum of digits of a number. Additionally, we will also see some more terms and concepts regarding the topic.

## Sum of digits in C Programming:

As discussed earlier, we use loops and other mathematical operations to perform the sum of digits of a number in C Programming. But in order for them to work we will have to follow a sequence of steps.

For instance, we first take a particular digit with the help of the modulus operator (%) to extract individual digits of a number and add them to the sum. We keep repeating this process inside a loop till the value of every digit is greater than 0. As a result, we’ll have a summation of the given number.

In addition, we can even replace the modulus operator with a string for storing the value of an integer. This can be done in case of a huge size of an integer.

In finding the sum of digits of a number we use 2 approaches:-

Recursion and Iteration.

### Recursion:

In Recursion, in the place of using loops like while or for, we use functions. It’s said to be quite similar to finding the individual digits of a number.

When a function copies itself to perform smaller problem, we call it a recursive function and we name the process as recursion. A program which has recursive functions involves a number of recursive calls.

Therefore, including a termination for the recursive functions is important. The recursion code is shorter than its iterative counterpart however, it is difficult to understand.

We cannot apply recursion to all the problems but it is useful for tasks that are divided into similar subtasks. For instance, we can apply recursion to sorting, searching, etc.

In general, iterative problems are more efficient methods than recursions since the function call is always overhead.

Also, the problems which we solve recursively, we can also solve using iterations. However, some problems are more efficient when we solve them using recursion. For example, factorial, Fibonacci series, etc.

### Iteration:

Whereas, in Iteration, we add the numbers using only loops such as while or for. Iterations are one of the most efficient methods in c programming. They allow you to calculate values as much a number as you want.

Iterations are best suited for almost all the problems. However, there are some exceptions.

Problems involving iterations always follow the following steps:

• They view the task as a sequence which is identical or nearly identical sub-tasks.
• Notice what changes are there in each iterations.
• Then, they express that change in terms of programming.
• They find when the program stops performing the task.
• Finally, they express the end condition as a condition that will ask about the condition in which the task should continue to repeat.

## C Programs for sum of digits of a number

Just like one of our previous articles, program for addition of two matrix in c++, this problem also has multiple approaches for solving.

We will go through three of those methods which will help you understand the problem better. In addition, you will also gain a clear knowledge about recursion and iteration which is discussed earlier.

Without wasting much time, let’s begin:

### C Program for sum of digits of a number using recursion:

#### Algorithm:

1. Start.
2. Define a sum function with one integer variable a.
3. Then, define the main function.
4. In the main function, declare n and res for the number and result respectively.
5. After that, enter the number by taking user input, read it.
6. Then, pass the value of n to the sum function.
7. Print the result.
8. Finally, define the sum function.
9. In the sum function, use if block to extract the digits and return the sum using recursive function sum.
10. Stop.

#### Program:

``// C Program to find Sum of Digits of a Number using Recursion#include <stdio.h> int sum (int a);int main(){    int n, res;    printf("Enter the number: ");    scanf("%d", &n);    res = sum(n);    printf("Sum of digits in %d is %d\n", n, res);    return 0;}int sum (int n){    if (n != 0)    {        return (n % 10 + sum (n / 10));    }    else    {       return 0;    }}``

#### Program Explanation:

The recursive function can be a little difficult to understand just by its code and algorithm. However, with proper program explanation, you will be able to go through it step by step.

At first, we are reading the number using n variable.

Then, we pass this value to the function sum(). This sum() function is used to calculate the sum of digits using recursion.

After that, let us study the sum() function closely,

Inside this function we first check if n is not equal to 0. This will be our checking condition.

If this is true the compiler will execute the statement inside the if block.

We then divide the value of n by 10 to get the individual digits.

After that, we add these values along with the modulus of the value of n variable.

Finally, we have the sum of digits of the numbers which we display as the result.

#### Output:

This is what we get as a result of the code above  :

In the above code, let us take a number 345.

Now, the digits of the number are 3,4 and 5. For adding them, we have to extract first using modulus.

So, we will evaluate 345 % 10 which gives 5. Then, we reduce the number by dividing it by 10. That is, 345/10 which gives 34. Now, we will take this 34 for next iteration.

Similarly, we extract all the digits that is 3,4 and 5. Then, we add all of them i.e. 3+4+5 = 12.

Thus, this is how we add the digits.

### C Program for sum of digits of a number using iteration:

This program will use a while loop to execute the sum of digits of a number in c program. As compared to the recursive method, we can say that this is less complex and easy to understand.

To have an overview, let us start with the algorithm of this program.

#### Algorithm:

1. Start.
2. Declare n, sum =0 and m for the number, sum and digits respectively.
3. Then, enter the number n as string, read it.
4. Using while loop, extract the digits using the modulus method and add the digits to the sum.
5. Finally, print the sum.
6. Stop.

#### Program:

``//C Program for the sum of digits of a number using iteration.#include<stdio.h>  int main()    {    int n,sum=0,m;    printf("Enter a number:");    scanf("%d",&n);    while(n>0)    {    m=n%10;    sum=sum+m;    n=n/10;    }    printf("Sum of digits of the given number is %d",sum);    return 0;  }   ``

#### Program Explanation:

The above code is the simplest c program for calculating the sum of digits of a number. The algorithm itself is easy to understand. Therefore, I don’t think any additional explanation is required for the code.

Just to explain the program briefly:

We take input from the user as the n variable.

In the while loop, which is our iteration block, we set the condition of execution till the value of n is not equal to 0.

Then, we use the modulus method similar to the recursive function method to extract the digits and add them to the sum variable.

Finally, we print the value of sum variable as the result.

#### Output:

This is what we get as a result of the code above  :

Here, let us take a number 341.

First, in the while loop, the condition 341 > 0 is true

Now, the digits of the number are 3,4 and 1. For adding them, we have to extract first using modulus.

So, we will evaluate 341 % 10 which gives 1. Then, we reduce the number by dividing it by 10. That is, 341/10 which gives 34. Now, we will take this 34 for next iteration.

Similarly, we extract all the digits that is 3,4 and 1. Then, we add all of them, i.e. 3+4+1 = 8.

Then, the checking condition will be false and compiler will come out of the loop.

Thus, this is how we add the digits.

### C Program for sum of digits of a number without using modulus:

Modulus method may seem like the only method that can be used for extracting the digits but it is not true. There is one more method in which we don’t have to use the modulus method to find out the digits and calculate their sum.

Let’s get right to it, starting with the algorithm.

#### Algorithm:

1. Start.
2. Declare the variables m, sum and t as integers.
3. Then, declare a n array variable.
4. Initialize s=0.
5. After that, initialize m  =0.
6. Repeat steps 7 and 8 till i is less than n.
7. Add sum = sum+ n[m].
8. Then, sum= sum-48.
9. Increment m by 1.
10. Finally, print sum.
11. Stop.

#### Program:

``//C Program for the sum of digits of a number without using modulus.#include <stdio.h>  int main()  {     int m, sum, t;     char n;     printf("Enter the number:");     scanf("%s", n);     sum = m = 0;     while (n[m] != '\0') {        t   = n[m] - '0';         sum = sum + t;        m++;     }     printf("sum of digits of the given number is  %d",sum);     return 0;  }  ``

#### Program Explanation:

In the above program we use array as a method to extract digits from the number.

At first we declare the required variables as usual. Then, we read the number.

We keep a variable m for acting as an index for each digit in n.

After that we extract the digits using a while loop and add them to the sum. We increase the index m by 1.

Finally, we print the sum as the result.

#### Output:

This is what we get as a result of the code above  :

Here , let us take a number 123.

However, the 123 is an array. Therefore, we represent it as n = {1,2,3} i.e n =1, n = 2, n = 3.

The while loop condition n is not null will be true.

For the first iteration, m= 0, t= n – null. And sum = 0+ n = 1

Then, m = 1. Therefore, t= n – null. And now sum = 1 + n= 1+ 2= 3.

Similarly, for the third and final iteration, sum = 3+ n = 3+ 3 = 6.

Finally, the checking condition will be false and the compiler will come out of the loop and print the result.

## Ending Note:

To sum it all up, we can say that the c program for sum of digits of a number is a very simple program. It has many applications such as checking for an Armstrong number. Harshad number, etc.

Armstrong number is a number whose sum of cube of digits is equal to the number. Thus, this sum of digits program with a little modification can be used to check for such a number.

A Harshad number or a Niven is a number which is divisible by the sum of its digits. Here also, the above code will help you to check for this kind of number.

Similarly, there are many other numbers and problems which use this code as a sub task in them. In other words, the c program for sum of digits of a number is very efficient and useful program. It is a must learn code for beginners.

See you in our next post!