Program to calculate sum of digits in C of a number using loop, explained logic and test cases.

Example,

Input number: 123
Output = 1+2+3 =6

Logic to find sum of digits:

  • Have two variables” sum” and “remainder” with initial value 0.
  • loop through the number
  • Get remainder of the number with modulus 10. e.g. 123 % 10 =3(last digit) and store in remainder.
  • add value of variable “sum” and remainder e.g. 0+3
  • Remove the last digit as it is processed and get the number again by dividing 10. e.g. 123/10 =12.
  • process the number 12 again in the loop and so on until value of input number becomes 0
  • loop end
  • sum variable will contain final result.

Program to calculate sum of digits in C

/*Example program to find sum of digits in C*/
#include <stdio.h>

int sumOfDigits(int number){

	//initialize values with 0
	int sum = 0;
	int remainder = 0;

	//Run the loop until value of number is 0
	while (number != 0) {
		//calculate remainder using % operator
		//lets say number is 123, so, remainder will be
		// 123 % 10 = 3
		remainder = number % 10;

		//add value of earlier sum+ remainder
		//e.g. 0+ 3
		sum = sum + remainder;

		//get remaing number i.e. 123/10 =12
		number = number / 10;

		//continue the number in loop until
		//value of number becomes 0.
		//once it is 0, sum variable will
		//have the summation result.

	}//loop end

	//return the sum
	return sum;
}

//Test program
int main()
{	
	int sum =0;
	int number = 0;

	printf("Enter a number:");
	scanf("%d",&number);

	sum = sumOfDigits(number);

	printf("Sum = %d ", sum);


	return 0;
}

Test Cases

Input:12345
Output = 15

Input: -12345
Output = -15

Input: 0
Output = 0

NOTES:

Within the while loop in C program above, the remainder statement can be eliminated as below.

while (number != 0) {

sum+=number%10;
number=number/10;
}

Related Posts