This tutorial is to find the sum of digits of a number using for loop and while loop in C. You need to have knowledge of the following topics in C.
Explanation:
To find the sum of the digits means to add all the digits present in the number. For example: consider a number 123, sum of the digits of 123 will be 1+2+3 = 6.
C Program to find the sum of the digits of a number using for loop
#include <stdio.h>
int main()
{
int num, sum = 0, rem, i;
printf("Enter a number: ");
scanf("%d", &num);
for (i = num; num != 0; num = num / 10)
{
rem = num % 10;
sum = sum + rem;
}
printf("Sum of digits of a number: %d", sum);
return 0;
}
Output:
Enter a number: 245
Sum of digits of a number: 11
C Program to find the sum of the digits of a number using while loop
To find the sum of a digit in c using while loop is similar to the for loop, here you need to initialize i with num after the input is taken from the user and i increment is done inside the while body as shown below.
#include <stdio.h>
int main()
{
int num, sum = 0, rem, i;
printf("Enter a number: ");
scanf("%d", &num);
i = num;
while (num != 0)
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
printf("Sum of digits of a number: %d", sum);
return 0;
}
Output:
Enter a number: 123
Sum of digits of a number: 6
C Program to find the sum of the digits of a number using recursion function
#include <stdio.h>
int sumDigits(int);
int main()
{
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
result = sumDigits(num);
printf("Sum of digits of a number: %d", result);
return 0;
}
int sumDigits(int n)
{
if (n == 0)
return 0;
return (n % 10 + sumDigits(n / 10)); //recursion call
}
Output:
Enter a number: 123
Sum of digits of a number: 6
Learn more on recursion.