C++ program for basic arithmetic operations. - coderforcoders

Search

Wednesday, 13 March 2019

C++ program for basic arithmetic operations.

Arithmetic operations in C++

Theory:

The arithmetic operations in  c++ is a simple program written using concepts like class and object. A class calculator is used to declare the data members num1, num2 and the result of the type int. Here we have used four member functions int add(), int sub(), int mul() and int div() for addition, subtraction, multiplication and division respectively. Each member function will performs its task and result a value which is the result to the mail function.
An object should be created to access the members of the class, in our program we have created a object called obj1 to the class calculator.

Logic:


C++ program for basic arithmetic operations uses the concepts of classes and objects. In this program we have also used the concept of switch statements. Switch statements are the conditional branching statements that takes one argument and executes the block of code which satisfies the condition(click here to learn more about switch statements). 

Syntax: 


switch(variable)
{
case 1: //block of code
            break;
case 2: //block of code
            break;
  .
  .
  .
case n: //block of code
            break;
default: //block of code
             break;
}

Default statement executes when no case statements matches.


Program:

C++ program for basic arithmetic operations.

#include<iostream>
using namespace std;
class calculator{
public:
int num1,num2,result;
int add()
{
return num1+num2;
}
int sub()
{
return num1-num2;
}
int mul()
{
return num1*num2;
}
int div()
{
return num1/num2;
}
};
int main()
{
calculator obj1;
int choice,res;
cout<<"Please enter two integer numbers\n";
cin>>obj1.num1>>obj1.num2;
cout<<"Please enter your choice\n";
cout<<"1. Addition \n2. subtraction \n3. Multiplication \n4. division\n";
cin>>choice;
switch(choice)
{
case 1: res=obj1.add();
cout<<"Result is "<<res;
break;
case 2: res=obj1.sub();
cout<<"Result is "<<res;
break;
case 3: res=obj1.mul();
cout<<"Result is "<<res;
break;
case 4: if(obj1.num2==0)
cout<<"Second number can not be zero\n";
else
{
res=obj1.div();
cout<<"Result is "<<res;
}
break;
default : cout<<"Invalid choice\n";
}
cout<<endl;
}

Output 1:


Please enter two integer numbers
10 5
please enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
1
Result is 15

Output 2:

Please enter two integer numbers
10 5
please enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
2
Result is 5

Output 3:

Please enter two integer numbers
10 5
please enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
3
Result is 50

Output 4:

Please enter two integer numbers
10 5
please enter your choice
1. Addition
2. Subtraction
3. Multiplication
4. Division
4
Result is 2



No comments:

Post a Comment