Write a function second_last_digit in C++ and call function that print the second last digit of the given number. The second last digit is being referred to the digit in the tens place in the given number.
For example, if the given number is 197, the second last digit is 9.
Note 1 - The second last digit should be returned as a positive number. i.e. if the given number is -197, the second last digit is 9.
Note 2 - If the given number is a single-digit number, then the second last digit does not exist. In such cases, the program should print -1. i.e. if the given number is 5, the second last digit should be print as -1.
#include <iostream>
using namespace std;
int second_last_digit(int x){
x = abs(x);
if(x >= 10){
return (x/10)%10;
}
else return -1;
}
int main(){
int x;
cout<<"Input the integer to find the second last digit.\n";
cin>>x;
if(abs(x) > 10)
cout<<"The second last digit of "<<x<<" is ";
cout<<second_last_digit(x);
return 0;
}
Comments
Leave a comment