Write a C++ program using function, where the jobs done by different functions are as follows:       

Name of Function

Purpose

main()

Asks the user to input two integer values x & y select any one operation 1.Add 2.Multiply 3.Divide 4.Substract function   main() calls the functions add(), multiply(), divide() &   subtract() according to the choice of user & also print the value returned by the called function.

add()

Receives two call by value parameters a & b sent by function main(), calculates their sum & returns the result to the main program.

multiply()

Receives one call by value parameter a & other call by reference parameter b from main program, multiplies a & b & returns the result to the main function.

divide()

Receives one call by value parameter a & other call by reference parameter b from main program, divides a & b & returns the result to the main function.

subtract()

Receives two call by reference parameters a & b sent by function main(), calculates their difference & returns the result to the main program.


#include<iostream.h>
#include<conio.h>

double a,b;

double add(double x,double y)
{
 double s;
 s=x+y;
 return(s);
}

double multiply(double x,double&y)
{
 double p;
 p=x*y;
 return(p);
}

double divide(double x,double&y)
{
 double d;
 d=x/y;
 return(d);
}

double substract(double&x,double&y)
{
 double s;
 s=x-y;
 return(s);
}

void main()
{
 clrscr();
 int ch;

 do
  {
   cout<<"Enter first number: ";
   cin>>a;
   cout<<"Enter second number: ";
   cin>>b;

   cout<<"1. Add."<<endl;
   cout<<"2. Multiply."<<endl;
   cout<<"3. Divide."<<endl;
   cout<<"4. Substract."<<endl;
   cout<<"5. Exit."<<endl;
   cout<<"Enter your choice: ";
   cin>>ch;

   switch(ch)
    {
      case 1: {
                  cout<<"\nThe sum is: "<<add(a,b);
                  break;
                  }
      case 2: {
                  cout<<"\nThe product is: "<<multiply(a,b);
                  break;
                 }
      case 3: {
                  cout<<"\nThe answer is: "<<divide(a,b);
                   break;
                 }
      case 4: {
                  cout<<"\nThe difference is: "<<substract(a,b);
                  break;
                 }
      case 5: {
                   break;
                 }
     default: {
                  cout<<"\nWrong choice entered.\n\n";
                  break;
                 }
    }  
    cout<<"\n\n";
   }
  while(ch!=5);
}

 

< Back