Create a Class calculator in C Private array of integers Int
Create a Class calculator in C++
Private array of integers
Int array [10] à 0 to 9
Functions add, mult , div , sub….each function will have 2 parameters
Operator +
Add 2 random number from the array from 2 object Caculator.
Ex: cal1 + cal2 = somenumber
Friend operator –
Same as part 3, but implement friend
Exception handling to check for overflow …..set rules for overflow e.g (if you have num larger than 15, then throw over load)
Excep divide by zero
Solution
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class calculator
{
private:
int array[10];
public:
calculator ()
{
}
calculator(int a[])
{
for(int i=0;i<10;i++)
{
array[i]=a[i];
}
}
int add(int n1,int n2)
{
int ans=n1+n2;
//if(ans>15)
//{
// cout<<enl<<\"Overflow occurs\";
// return -1;
//}
return ans;
}
int sub(int n1,int n2)
{
return n1-n2;
}
int mult(int n1,int n2)
{
return n1*n2;
}
double div(int n1,int n2)
{
if(n2==0)
{
cout<<endl<<\"Divide by zero exception\";
return -1;
}
return (n1/n2);
}
calculator operator+(calculator &c)
{
srand (time(NULL));
int pos1=(10 *rand()/RAND_MAX);
int pos2=(10 *rand()/RAND_MAX);
int n1=array[pos1];
int n2=c.array[pos2];
int arr[1];
arr[0]=(n1+n2);
calculator temp(arr);
return temp;
}
calculator operator-(calculator &c)
{
srand (time(NULL));
int pos1=(10 *rand()/RAND_MAX);
int pos2=(10 *rand()/RAND_MAX);
int n1=array[pos1];
int n2=c.array[pos2];
int arr[1];
arr[0]=(n1-n2);
calculator temp(arr);
return temp;
}
};
int main()
{
int a1[]={10,5,6,2,9,12,8,11,13,1};
calculator cal1(a1);
cout<<endl<<\"Addition of 5, 10: \"<<cal1.add(5,10);
cout<<endl<<\"Subtraction of 10, 5: \"<<cal1.sub(10,5);
cout<<endl<<\"Multiplication of 5, 10: \"<<cal1.mult(5,10);
cout<<endl<<\"Division of 10, 0: \";
int ans=cal1.div(10,0);
if(ans!=-1)
cout<<ans;
int a2[]={4,6,12,7,9,1,10,11,5,14};
calculator cal2(a2);
calculator cal3;
cal3=cal1+cal2;
}
![Create a Class calculator in C++ Private array of integers Int array [10] à 0 to 9 Functions add, mult , div , sub….each function will have 2 parameters Operato Create a Class calculator in C++ Private array of integers Int array [10] à 0 to 9 Functions add, mult , div , sub….each function will have 2 parameters Operato](/WebImages/24/create-a-class-calculator-in-c-private-array-of-integers-int-1061415-1761554550-0.webp)
![Create a Class calculator in C++ Private array of integers Int array [10] à 0 to 9 Functions add, mult , div , sub….each function will have 2 parameters Operato Create a Class calculator in C++ Private array of integers Int array [10] à 0 to 9 Functions add, mult , div , sub….each function will have 2 parameters Operato](/WebImages/24/create-a-class-calculator-in-c-private-array-of-integers-int-1061415-1761554550-1.webp)