sum of digits in c++

To find the sum of digits in C++, you can use the following steps:

  1. Declare and initialize variables: Declare an integer variable to store the sum and another integer variable to store the number whose digits you want to find the sum of.
  2. Prompt for user input: Use the "cout" statement to prompt the user to enter a number.
  3. Read user input: Use the "cin" statement to read the user's input and store it in the variable declared in step 1.
  4. Calculate the sum: Use a loop to iterate through each digit of the number. Inside the loop, extract the last digit of the number using the modulo operator (%) and add it to the sum variable. Then, divide the number by 10 to remove the last digit.
  5. Repeat step 4 until the number becomes 0: Continue the loop until the number becomes 0.
  6. Display the sum: Use the "cout" statement to display the sum of the digits.

Here is an example code snippet that demonstrates how to find the sum of digits in C++:

#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter a number: ";
    cin >> num;

    while (num != 0) {
        sum += num % 10;
        num /= 10;
    }

    cout << "Sum of the digits: " << sum;

    return 0;
}

This code will prompt the user to enter a number, calculate the sum of its digits, and display the result.