C++ Program: Sum of Digits
The sum of digits program in C++ is a simple program that calculates the sum of individual digits of a given number.
Syntax
#include <iostream>
using namespace std;
int main() {
int num, sum = 0, rem;
cout << "Enter a number: ";
cin >> num;
while (num != 0) {
rem = num % 10;
sum += rem;
num /= 10;
}
cout << "Sum of digits: " << sum << endl;
return 0;
}
Example
Enter a number: 1234
Sum of digits: 10
Explanation
In the above example, we first ask the user to enter a number. We then use a while loop to calculate the sum of individual digits. Inside the while loop, we use the modulus operator (%) to get the remainder (last digit) of the number. We add the remainder to the sum and then divide the number by 10 to remove the last digit. We continue this process until the number becomes 0. Finally, we output the sum of digits.
Use
The sum of digits program is used to calculate the sum of individual digits of a given number. It can be used in various applications that require this functionality such as calculating checksums, verifying user input, and encryption algorithms.
Important Points
- The sum of digits program calculates the sum of individual digits of a given number.
- The modulus operator (%) is used to get the remainder (last digit) of the number.
- The sum is updated by adding the remainder and dividing the number by 10.
- The program continues until the number becomes 0.
Summary
In summary, the sum of digits program is a simple program that can calculate the sum of individual digits of a given number. It is useful in various applications that require this functionality such as calculating checksums and encryption algorithms.