/* * C program to accept an integer & find the sum of its digits */ #include <stdio.h> void main() { long num, temp, digit, sum = 0; printf("Enter the number \n"); scanf("%ld", &num); temp = num; while (num > 0) { digit = num % 10; sum = sum + digit; num /= 10; } printf("Given number = %ld\n", temp); printf("Sum of the digits %ld = %ld\n", temp, sum); }
Program Explanation
- Take an integer as a input and store it in the variable num.
- Initialize the variable sum to zero.
- Divide the input integer by 10 and obtain its remainder & quotient.
- Store the remainder in the variable digit.
- Increment the variable sum with variable digit.
- Store the quotient into the variable num.
- Repeat the steps 3,4,5,6 with the new num.
- Do step 7 until the quotient becomes zero.
- Print the variable sum as output and exit.
No comments:
Post a Comment