###
__
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