#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the number : ");
scanf("%d", &n);
while (n != 0){
int last_digit = n % 10;
sum += last_digit;
n = n / 10; // remove last digit
}
printf("Sum of digits : %d", sum);
}
Above C code takes the number as input from the user and calculate the sum of the digits. It first initializes the variable ‘sum’ to 0. Then prints or prompts the user to enter an integer using the printf function and reads the input using the scanf function.
The code entters a while loop that loop continues until the value of n becomes 0. In each iteration of the loop, it computes the last digit of 'n' using the modulo operator and adds it to ‘sum’. It then removes the last digit from ‘n’ by dividing it by 10.
Finally, it prints the sum of digits using the printf() function.
1. Set n = 0
2. Set sum = 0
3. Display "Enter the number : "
4. Read integer n from user using scanf
5. While n is not equal to 0, repeat the following:
a. Set last_digit = n % 10
b. Set sum = sum + last_digit
c. Set n = n / 10
6. Display "Sum of digits : " followed by the value of sum using printf
Learn More Do More. Happy Coding!.
Comments
Oops!