print each number of digit c++
To print each digit of a number in C++, you can follow the following steps:
- Declare a variable of an appropriate data type to store the number.
int number;
- Prompt the user to enter the number.
cout << "Enter a number: ";
cin >> number;
- Initialize a variable to store the remainder of the number when divided by 10.
int digit;
- Use a loop to extract each digit of the number until the number becomes zero.
while (number != 0) {
digit = number % 10;
cout << digit << " ";
number = number / 10;
}
- Print each digit as it is extracted.
cout << digit << " ";
- Update the number by dividing it by 10 to remove the rightmost digit.
number = number / 10;
- Repeat steps 4 to 6 until the number becomes zero.
Here is the complete code:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int digit;
while (number != 0) {
digit = number % 10;
cout << digit << " ";
number = number / 10;
}
return 0;
}
This code prompts the user to enter a number and then prints each digit of the number separated by a space.