Digits in c++

Certainly! Here's an example of handling digits in C++:

#include <iostream>
using namespace std;

int main() {
    int number = 12345;

    // Counting digits in the number
    int count = 0;
    int temp = number;
    while (temp != 0) {
        temp /= 10;
        count++;
    }

    cout << "Number of digits: " << count << endl;

    // Extracting digits and printing them separately
    cout << "Digits extracted: ";
    while (number != 0) {
        int digit = number % 10;
        cout << digit << " ";
        number /= 10;
    }

    return 0;
}

Explanation:

  1. #include <iostream>: Includes the input/output stream library.

  2. using namespace std;: Allows the use of standard C++ libraries without explicitly using the std:: prefix.

  3. int main() { ... }: The main function where the program execution begins.

  4. int number = 12345;: Initializes an integer variable number with the value 12345.

  5. int count = 0;: Initializes a variable count to store the count of digits.

  6. int temp = number;: Creates a temporary variable temp to store the number for digit counting purposes.

  7. while (temp != 0) { ... }: Loop to count the number of digits in number.

  8. temp /= 10; count++;: Divides temp by 10 in each iteration to remove the last digit, incrementing count for each digit.

  9. cout << "Number of digits: " << count << endl;: Outputs the count of digits.

  10. while (number != 0) { ... }: Loop to extract and print each digit of number.

  11. int digit = number % 10;: Calculates the last digit of number using the modulo operator %.

  12. cout << digit << " ";: Outputs the extracted digit.

  13. number /= 10;: Removes the last digit from number.

  14. return 0;: Indicates successful completion of the main() function.