Question:

Write a program in C++ to accept a number then display how many digits it contains and the sum of its digits.

Show Hint

The modulo operator (`% 10`) is perfect for getting the last digit of a number, and integer division (`/ 10`) is perfect for removing it. Repeating this process in a loop is a classic way to process all digits of a number.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

C++ Program: Count Digits and Sum of Digits

#include <iostream>

int main(){
    int number;
    int originalNumber; // To store the original number for display
    int digitCount = 0;
    int sumOfDigits = 0;

    // Prompt the user to enter a number
    std::cout << "Enter an integer: ";
    std::cin >> number;

    // Store the original number as it will be modified
    originalNumber = number;

    // Handle the case of input being 0
    if (number == 0){
        digitCount = 1;
    } else {
        // Make the number positive if it's negative
        if (number < 0){
            number = -number;
        }

        // Loop until the number becomes 0
        while (number > 0){
            // Get the last digit using the modulo operator
            int digit = number % 10;
            
            // Add the digit to the sum
            sumOfDigits += digit;
            
            // Increment the digit count
            digitCount++;
            
            // Remove the last digit by integer division
            number = number / 10;
        }
    }

    // Display the results
    std::cout << "The number " << originalNumber << " contains " << digitCount << " digits." << std::endl;
    std::cout << "The sum of its digits is: " << sumOfDigits << std::endl;

    return 0;
}

Corrections Made:

  • Replaced malformed entities like & Lt; with correct HTML entity <.
  • Ensured all angle brackets are correctly escaped for HTML display.
Was this answer helpful?
0
0