first and last digit of a number in c++
To find the first and last digit of a number in C++, you can follow these steps:
- Get the input number from the user.
- Convert the number to a string using the
to_string()
function. This will allow us to access individual digits easily. - Retrieve the first digit by accessing the first character of the string.
- Retrieve the last digit by accessing the last character of the string.
- Convert the first and last digits back to integers using the
stoi()
function if necessary.
Here is the code snippet that demonstrates this process:
#include <iostream>
#include <string>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::string numberString = std::to_string(number);
int firstDigit = numberString[0] - '0';
int lastDigit = numberString[numberString.length() - 1] - '0';
std::cout << "First digit: " << firstDigit << std::endl;
std::cout << "Last digit: " << lastDigit << std::endl;
return 0;
}
In this code, we use the std::to_string()
function to convert the number
variable to a string. We then access the first digit by using numberString[0]
and the last digit by using numberString[numberString.length() - 1]
. The - '0'
part is used to convert the characters to their integer equivalents. Finally, we output the first and last digits using std::cout
.