Sum of digits in C
0 246
Calculating the sum of digits in a number involves extracting each digit from the given number and adding them together.
There are several methods to compute the sum of digits in C, ranging from using arithmetic operations to looping through the digits.
Method 1: Using Arithmetic Operations
Extract the Last Digit: Use the modulo (%) operator to extract the last digit of the number.
Add to Sum: Add the extracted digit to a variable (sum).
Remove the Last Digit: Use integer division (/) to remove the last digit from the number.
Repeat: Continue the process until the number becomes zero.
Program to Calculate Sum of Digits
//Program to Calculate Sum of Digits #include<stdio.h>int main() { int number, sum = 0, remainder; printf("Enter an integer: "); scanf("%d", &number); while (number != 0) { remainder = number % 10; // Extract the last digit sum += remainder; // Add to sum number /= 10; // Remove the last digit } printf("Sum of digits: %d\n", sum); return 0; }
Output:
Enter an integer: 23 Sum of digits: 5
Method 2: Using Recursion
Base Case: If the number is less than 10, return the number.
Recursive Step: Extract the last digit, add it to the sum of the remaining digits (recursive call).
Program using Recursion
//Program using Recursion: #include<stdio.h>int sumOfDigits(int number) { if (number < 10) { return number; } return (number % 10) + sumOfDigits(number / 10); } int main() { int number, sum; printf("Enter an integer: "); scanf("%d", &number); sum = sumOfDigits(number); printf("Sum of digits: %d\n", sum); return 0; }
Output:
Enter an integer: 45 Sum of digits: 9
Key Points:
% Operator: Used to extract the last digit.
/ Operator: Used to remove the last digit.
Loop vs Recursion: Both methods are valid and have their pros and cons.
The recursive method might be less efficient for large numbers due to function call overhead.
Share:
Comments
Waiting for your comments