# C Program to Add Digits of a Number

• Write a c program to find sum of digits of a number.
• Write a C program to add digits of a number.

To add digits of a number we have to remove one digit at a time we can use '/' division and '%' modulus operator. Number%10 will give the least significant digit of the number, we will use it to get one digit of number at a time. To remove last least significant digit from number we will divide number by 10.

Sum of digits of 2534 = 2 + 5 + 3 + 4 = 14

Algorithm to find sum of digits of a number
• Get least significant digit of number (number%10) and add it to the sum variable.
• Remove least significant digit form number (number = number/10).
• Repeat above two steps, till number is not equal to zero.
For example
Reading last digit of a number : 1234%10 = 4
Removing last digit of a number : 1234/10 = 123

## C Program to add digits of a number using loop

This program takes a number as input from user using scanf function. Then it uses a while loop to repeat above mentioned algorithm until number is not equal to zero. Inside while loop, on line number 14 it extract the least significant digit of number and add it to digitSum variable. Next it removes least significant digit from number in line number 17. Once while loop terminates, it prints the sum of digits of number on screen.

```/*
* C Program to find sum of digits of a number
*/
#include <stdio.h>
#include <conio.h>

int main(){
int number, digitSum = 0;
printf("Enter a number : ");
scanf("%d", &number);
while(number != 0){
/* get the least significant digit(last digit)
of number and add it to digitSum */
digitSum += number % 10;
/* remove least significant digit(last digit)
form number */
number = number/10;
}
printf("Sum of digits : %d\n", digitSum);
getch();
return 0;
}
```
Program Output
```Enter a number : 1653
Sum of digits : 15
```

## C program to find sum of digits of a number using function

This program uses a user defined function 'getSumOfDigit' to find the sum of digits of a number. It implements the algorithm mentioned above using / and % operator.

```/*
* C Program to print sum of digits of a number using number
*/
#include <stdio.h>
#include <conio.h>

int main(){
int num;
printf("Enter a number : ");
scanf("%d", &num);
printf("Sum of digits of %d is %d\n", num, getSumOfDigit(num));
getch();
return 0;
}

/*
* Function to calculate sum of digits of a number
*/
int getSumOfDigit(int num){
int sum = 0;
while(num != 0){
/* num%10 gives least significant digit of num */
sum = sum + num%10;
num = num/10;
}
return sum;
}
```
Program Output
```Enter a number : 5423
Sum of digits of 5423 is 14
```

Related Topics
 C program to reverse a number C program to check a number is palindrome or not C Program to find nPr and nCr C program to reverse a number C program to convert string to integer C program to swap two numbers C program to generate armstrong numbers List of all C programs