C Program to find Sum of Digits in a Number

CodingTute

C Program to find Sum of Digits

In this example, you will learn to find the sum of digits in a given number using C Programming.

For example, 123 should give the output 6 (1+2+3).

C Program to find Sum of Digits in a Number

#include <stdio.h>
int main() {
  long n;
  int sum = 0;
  printf("Enter an integer: ");
  scanf("%ld", &n);
 
  while(n!=0){
      sum+=(n%10);  // sum = sum + (n%10)
      n/=10;   //will remove the last digit
  }

  printf("Sum of digits: %d", sum);
}

Output

Enter an integer: 1234
Sum of digits: 10

Explanation

We take input from user and store it in a variable n. We will initialize a variable sum=0. Now we will run the while loop till n becomes 0 and inside the loop, we will remove the last digit of n per each iteration. n%10 returns the last digit of n and n/10 removes the last digit of n.

So sum+=(n%10) will add the last digit of n at each iteration of the loop.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Exit mobile version