Write a program in which users enter 5 numbers using for loop and all these numbers will store in an array. After that program will add these five numbers and show the result. Your program must support the concept of operator overloading.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
#include <iostream> using namespace std; class T4Tutorials { private: int arr[5]; public: T4Tutorials() {} friend T4Tutorials operator+(T4Tutorials const &, T4Tutorials const &); friend T4Tutorials operator+(T4Tutorials const &, int const &); friend T4Tutorials operator+(int const &, T4Tutorials const &); void setArr() { for (int i = 0; i < 5; i++) { cout << "Enter element " << i+1 << ": "; cin >> arr[i]; } } void displayArr() { for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } cout << endl; } }; T4Tutorials operator+(T4Tutorials const &FirstObject, T4Tutorials const &SecondObject) { T4Tutorials res; for (int i = 0; i < 5; i++) { res.arr[i] = FirstObject.arr[i] + SecondObject.arr[i]; } return res; } T4Tutorials operator+(T4Tutorials const &FirstObject, int const &num) { T4Tutorials res; for (int i = 0; i < 5; i++) { res.arr[i] = FirstObject.arr[i] + num; } return res; } T4Tutorials operator+(int const &num, T4Tutorials const &SecondObject) { T4Tutorials res; for (int i = 0; i < 5; i++) { res.arr[i] = num + SecondObject.arr[i]; } return res; } int main() { T4Tutorials FirstObject, SecondObject, obj3; FirstObject.setArr(); SecondObject.setArr(); obj3 = FirstObject + SecondObject; // Adding two arrays using operator overloading cout << "Resultant array after adding two arrays: "; obj3.displayArr(); int num; cout << "Enter a number to add to the array: "; cin >> num; obj3 = FirstObject + num; // Adding an array and a number using operator overloading cout << "Resultant array after adding a number to the array: "; obj3.displayArr(); obj3 = num + SecondObject; // Adding a number and an array using operator overloading cout << "Resultant array after adding a number to the array: "; obj3.displayArr(); return 0; } |
Output
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Enter element 1: 6
Enter element 2: 7
Enter element 3: 8
Enter element 4: 9
Enter element 5: 7
Resultant array after adding two arrays: 7 9 11 13 12
Enter a number to add to the array: 6
Resultant array after adding a number to the array: 7 8 9 10 11
Resultant array after adding a number to the array: 12 13 14 15 13