In this exercise, you will be required to use pointers and pointer to functions to update the balance in an account
Part 1
Pointers to Update Account Balance
Problem Statement
In this part you are required to:
- Make functions
- Withdraw:
- Is a
void
function. - Takes two parameters:
- a pointer to the balance in account.
- the amount to be withdrawn from account, also of type
double
.
- Add a check so that the amount is only withdrawn if it is less then total balance in the account. Otherwise it should display: “You are broke. You don’t have enough money. Go away”
- Is a
- Deposit:
- Takes two parameters:
- a pointer to the balance in account.
- the amount to be deposited in the account, also of type
double
.
- The function should add the required amount into the account.
- Takes two parameters:
- Withdraw:
Write your code below. It is recommended that you try solving the exercise yourself before viewing the solution.
Good Luck!
void withdraw(double* balance, double amount) {}void deposit(double* balance, double amount) {}
Part 2
Pointers To Functions
Problem Statement
Now let’s implement the above example but by using Pointers to Functions.
In this part you are required to:
- Declare a pointer to functions
- Withdraw:
- Deposit:
Note: The code for both
Withdraw
andDeposit
functions have already been prepended (not visible to you) in the code widget below hence you don’t need to rewrite them as you’ve done that above already.
- Call both these functions in the
main
according to the instructions given in the code widget below.
Hint
- Declare and use a pointer named
balance
in your code below to update and keep track of the total balance in the account.
Write your code below. It is recommended that you try solving the exercise yourself before viewing the solution.
Good Luck!
//declare a void pointer to functions "withdraw" and "deposit" hereint main() {// declare a pointer here to keep track of balance in the account and NAME it "balance"double harry_account_balance = 0;//initialize the "balance" pointer such that it keeps track of harry_account_balancecout << "Harry's Balance at start is: "; //print the balance herecout <<endl;double amount = 1000.00; //setting the amount to be deposited/* Make a deposit of the amount above by calling pointer to the appropriate function */cout << "Balance in harry account is: "; //print the balance herecout<<endl;amount = 500; //setting amount to 500/* Withdraw the amount set above by calling pointer to the appropriate function */cout << "Balance after withdrawing cash is: "; //print the balance herecout<<endl;amount = 3000; //setting amount to 3000cout << "Withdrawing "<<amount << " now" <<endl;/* Withdraw the amount set above by calling pointer to the appropriate function */}
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy