Write a C++ program using the concept of OOP to find the summation of first and last digits of a number


Write a C++ program using the concept of OOP to find the summation of the first and last digits of a number.

Algorithm:

  1. Create a Number class with private variable num to store the number whose first and last digits are to be found.
  2. 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.
  3. 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.
  4. 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.
  5. In the main() function, prompt the user to enter a number.
  6. Create a Number object with the number entered by the user.
  7. Call the sumFirstLast() method of the Number object to find the summation of first and last digits of the entered number.
  8. Print the summation of first and last digits of the entered number
  9. 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