CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #112

Counting Failures in a Loop

easyExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3 
4int withdraw(int balance, int amount) {
5 if (amount > balance) {
6 throw std::runtime_error("insufficient funds");
7 }
8 return balance - amount;
9}
10 
11int main() {
12 int balance = 100;
13 int amounts[] = {30, 90, 50, 40};
14 int ok = 0;
15 int failed = 0;
16 for (int amount : amounts) {
17 try {
18 balance = withdraw(balance, amount);
19 ok++;
20 std::cout << "withdrew " << amount << ", balance " << balance << "\n";
21 } catch (const std::runtime_error& e) {
22 failed++;
23 std::cout << "refused " << amount << ": " << e.what() << "\n";
24 }
25 }
26 std::cout << ok << " ok, " << failed << " failed, balance " << balance << "\n";
27 return 0;
28}

🎯 Your Answer