Pages

Tuesday, July 24, 2012

Function that returns a value and Passes data from one function to another


Function that returns a value and Passes data (Passing of Arguments) from one function to another

A function may send data to another function using parameters or arguments.
Arguments are data within the opening and closing parenthesis of the functions. They are like variable storing information that can be access outside of the function. Remember that variable inside the function is only accessible in that function and cannot be used outside the function.

Syntax:

datatype functionname(datatype param1, datatype param2,…)
{
    //body of a function with return value.
}

Sample Program: Bank Transaction Simulation using function that returns a value and passes data from one function to another

#include<iostream>
using namespace std;

float withdraw(float balance)
{
float wamount;
    cout<<"Amount to withdraw: ";
    cin>>wamount;
    return (balance – wamount);
}

float deposit(float balance)
{
float damount;
    cout<<"Amount to deposit: ";
    cin>>damount;
    return (balance – damount);
}

float BalanceInquiry(float balance)
{
    return balance;
}

int main()
{
char opt;
float obalance;
float rebalance;
cout<<"Enter your opening balance: ";
cin>>obalance;
cout<<endl<<endl;
    cout<<"Choose your Action: "<<endl
         <<"\t<W>ithdraw"<<endl
         <<"\t<D>eposit"<<endl
         <<"\t<B>alance Inquiry"<<endl
         <<"Action -> ";

    cin>>opt;

    switch(opt)
    {
         case 'w':
        case 'W': rbalance = withdraw(obalance);
                  break;
        case 'd': rbalance = deposit(obalance);
                  break;
        case 'b':
        case 'B': rbalance = BalanceInquiry();
break;
        default:  cout<<"Invalid input!"<<endl;
         system("pause");
                  return 0;
                  break;
  }
  cout<<"Remaining balance: "<<rbalance<<endl<<endl;
 
  system("pause");
  return 0;
}

1 comment:

  1. There are 4 functions in the program. One is the main function that calls the other function and passes data to them. The other three are withdraw(), deposit() and BalanceInquiry(). Each function is related to its identifier where it does exactly as it states. For example, the function withdraw deducts the amount entered by the user to the balance.

    ReplyDelete