Write a C++ program using the concept of OOP to find the first and last digits of a number.
Algorithm:
- Create a Number class with private variable num to store the number whose first and last digits are to be found.
- Define a public method firstAndLast() in the class to find the first and last digits of the stored number by using mathematical operations and prints the result.
- In the main() function, prompt the user to enter a number.
- Create a Number object with the number entered by the user.
- Call the firstAndLast() method of the Number object to find and print the first and last digits of the entered number.
- End the program.
Coding:
#include <iostream>
using namespace std;
class Number {
private:
int num;
public:
Number(int x) {
num = x;
}
void firstAndLast() {
int first = num;
while (first >= 10) {
first /= 10;
}
int last = num % 10;
cout << "First digit: " << first << endl;
cout << "Last digit: " << last << endl;
}
};
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
Number n(num);
n.firstAndLast();
return 0;
}
/*
Input:
Enter a number: 123456789
Output:
First digit: 1
Last digit: 9
*/
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment