Write a C++ program using the concept of OOP to find the summation of 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 firstDigit() in the class to find the first digit of the stored number by using mathematical operations and return the result.
- Define a public method lastDigit() in the class to find the last digit of the stored number by using mathematical operations and return the result.
- Define a public method sumFirstLast() in the class to find the summation of first and last digits of the stored number by using mathematical operations and return 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 sumFirstLast() method of the Number object to find the summation of first and last digits of the entered number.
- Print the summation of 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; } int firstDigit() { int first = num; while (first >= 10) { first /= 10; } return first; } int lastDigit() { return num % 10; } int sumFirstLast() { return firstDigit() + lastDigit(); } }; int main() { int num; cout << "Enter a number: "; cin >> num; Number n(num); cout << "Sum of first and last digit: " << n.sumFirstLast() << endl; return 0; }
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment