Challenge: Bank Account
Completed
Write a BankAccount class with a private balance starting at 0. Read n commands, each deposit X or withdraw X. A withdrawal bigger than the balance must be refused: print Refused: X. At the end print Balance: B.
Input
n, then n commands.
Output
One Refused line for each refused withdrawal, then the balance line.
Example
Input
4 deposit 100 withdraw 30 withdraw 200 deposit 5
Output
Refused: 200 Balance: 75
Editor
C++
Hints
withdraw can return a bool: true if it worked.
Read each command as a string and a number.
Solution explanation
Because balance is private, the only way to change it is through deposit and withdraw, which enforce the rules.
Show solution
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
int balance = 0;
public:
void deposit(int amount) {
balance += amount;
}
bool withdraw(int amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
int getBalance() const {
return balance;
}
};
int main() {
int n;
cin >> n;
BankAccount acc;
for (int i = 0; i < n; i++) {
string command;
int amount;
cin >> command >> amount;
if (command == "deposit") {
acc.deposit(amount);
} else if (!acc.withdraw(amount)) {
cout << "Refused: " << amount << "\n";
}
}
cout << "Balance: " << acc.getBalance() << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module