C Programming

Solved Example

Practice Questions

Exercise Question

Calculate sum of digits of a 5 digits number

Objective

Input a five digit number and write a program to find the sum of its digits. For example: if number entered is 23412 the sum is 2 + 3 + 4 + 1 + 2 = 12

Program / Solution

#include<stdio.h>
int main() {
	int n;
	int dig1,dig2,dig3,dig4,dig5;
	int sum;
	
	printf("Enter five digit number: ");
	scanf("%d",&n);
	
	dig1 = n % 10;
	n = n / 10;
	
	dig2 = n % 10;
	n = n / 10;
	
	dig3 = n % 10;
	n = n / 10;
	
	dig4 = n % 10;
	n = n / 10;
	
	dig5 = n; //finally 5th digit remains in number
	
	
	sum = dig1 + dig2 + dig3 + dig4 + dig5;
	
	printf("Sum = %d",sum);
	return 0;
}

Sample Output:

Enter five digit number: 21415
Sum = 13