C Sum of Digits Program
The Sum of Digits program calculates the sum of all individual digits of a given integer. For example, if the input number is 123
, the output will be 1 + 2 + 3 = 6
.
Logic of the Sum of Digits Program:
- Input a number from the user.
- Initialize a variable to hold the sum of the digits.
- Extract each digit of the number using modulus and division operations:
- Use the modulus operator
%
to get the last digit. - Add this digit to the sum.
- Use integer division
/
to remove the last digit.
- Use the modulus operator
- Repeat until all digits have been processed (when the number becomes zero).
- Print the final sum of the digits.
Program:
Here’s a C program to calculate the sum of digits of a given number:
Explanation:
Variables:
int num
: Holds the number inputted by the user.int sum
: Initializes to zero and will accumulate the sum of the digits.int remainder
: Used to store the current digit being processed.
Input:
- The program prompts the user to enter an integer.
Handling Negative Numbers:
- The program converts the number to positive if it is negative using the conditional operator.
Sum Calculation:
- A
while
loop runs untilnum
becomes zero. - Inside the loop:
- The last digit of
num
is obtained usingnum % 10
. - This digit is added to
sum
. - The last digit is removed from
num
usingnum /= 10
.
- The last digit of
- A
Output:
- Finally, the program prints the total sum of the digits.
Sample Output:
Example 1:
Example 2:
Example 3:
Key Points:
- Digit Extraction: The program effectively extracts each digit from the number using modulus and division.
- Handling Negatives: It gracefully handles negative input by converting it to positive before processing.
- Efficiency: The program runs in linear time relative to the number of digits in the input number, making it efficient for this operation.
- User Interaction: The program is user-friendly, prompting for input and providing clear output.