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:
#include <iostream>
: Includes the input/output stream library.using namespace std;
: Allows the use of standard C++ libraries without explicitly using thestd::
prefix.int main() { ... }
: The main function where the program execution begins.int number = 12345;
: Initializes an integer variablenumber
with the value 12345.int count = 0;
: Initializes a variablecount
to store the count of digits.int temp = number;
: Creates a temporary variabletemp
to store the number for digit counting purposes.while (temp != 0) { ... }
: Loop to count the number of digits innumber
.temp /= 10; count++;
: Dividestemp
by 10 in each iteration to remove the last digit, incrementingcount
for each digit.cout << "Number of digits: " << count << endl;
: Outputs the count of digits.while (number != 0) { ... }
: Loop to extract and print each digit ofnumber
.int digit = number % 10;
: Calculates the last digit ofnumber
using the modulo operator%
.cout << digit << " ";
: Outputs the extracted digit.number /= 10;
: Removes the last digit fromnumber
.return 0;
: Indicates successful completion of themain()
function.