Here is a C program to find sum of 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
- 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.
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.
#include <stdio.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); return 0; }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.
#include <stdio.h> int main(){ int num; printf("Enter a number : "); scanf("%d", &num); printf("Sum of digits of %d is %d\n", num, getSumOfDigit(num)); return 0; } int getSumOfDigit(int num){ int sum = 0; while(num != 0){ sum = sum + num%10; num = num/10; } return sum; }Output
Enter a number : 5423 Sum of digits of 5423 is 14
Related Topics