how to get the last digit of a number

To get the last digit of a number in C++, you can use the modulo operator (%) to find the remainder when dividing the number by 10. The remainder will be the last digit of the number.

Here is an example code snippet:

#include <iostream>

int main() {
    int number = 12345;
    int lastDigit = number % 10;

    std::cout << "The last digit of " << number << " is " << lastDigit << std::endl;

    return 0;
}

Explanation:

  1. We declare a variable number and initialize it with the desired number, in this case, 12345.
  2. We declare another variable lastDigit and assign it the value of number modulo 10 (number % 10). The modulo operator calculates the remainder when number is divided by 10, giving us the last digit.
  3. We use the std::cout object to print the result, concatenating the strings with the values of number and lastDigit.
  4. Finally, we return 0 to indicate successful execution of the program.

When you run this code, the output will be:

The last digit of 12345 is 5

This demonstrates how to obtain the last digit of a number in C++ using the modulo operator.