66.4k views
4 votes
The homework is based on E5.3, write a program that has the following methods. a. int firstDigit(int n) , returning the first digit of the argument b. int lastDigit(int n) , returning the last digit of the argument c. int digits(int n) , returning the number of digits of the argument For example, firstDigit(1729) is 1, last digit(1729) is 9, and digits(1729) is 4. d. a main method that i) ask the user to input a non-negative integer ii) print out the number of digits, the first digit and the last digit of the input by calling the methods you defined iii) repeat the above process (i and ii) until the user input a negative number

1 Answer

4 votes

Answer:

C++ code is explained

Step-by-step explanation:

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int firstDigit(int n){

// Converting int to string

ostringstream convert;

convert << n;

string s = convert.str();

char first_char = s[0];

int first_int = first_char - '0';

return first_int;

}

int lastDigit(int n){

// Converting int to string

ostringstream convert;

convert << n;

string s = convert.str();

char last_char = s[s.length() - 1];

int last_int = last_char - '0';

return last_int;

}

int digits(int n){

// Converting int to string

ostringstream convert;

convert << n;

string s = convert.str();

int length = s.length();

return length;

}

int main() {

int number;

cout << "Enter integer: " << endl;

cin >> number;

cout << "The first digit of the number is " << firstDigit(number) << endl;

cout << "The last digit of the number is " << lastDigit(number) << endl;

cout << "The number of digits of the number is " << digits(number) << endl;

}

User Keydon
by
6.2k points