Question 8
Back to Exercise
Write a menu-driven ATM: 1 = balance, 2 = deposit, 3 = withdraw, 4 = exit. Refuse invalid choices and withdrawals larger than the balance.
Input: 1, 2 500, 3 200, 3 5000, 9, 4
Solution
#include <stdio.h>
int main(void) {
int balance = 1000, choice, amount;
do {
if (scanf("%d", &choice) != 1)
break; /* input ended */
switch (choice) {
case 1:
printf("Balance: %d\n", balance);
break;
case 2:
if (scanf("%d", &amount) == 1 && amount > 0) {
balance += amount;
printf("Deposited %d, balance %d\n", amount, balance);
}
break;
case 3:
if (scanf("%d", &amount) != 1)
break;
if (amount > balance)
puts("Insufficient balance");
else {
balance -= amount;
printf("Withdrew %d, balance %d\n", amount, balance);
}
break;
case 4:
puts("Goodbye");
break;
default:
puts("Invalid choice");
}
} while (choice != 4);
return 0;
}
Balance: 1000 Deposited 500, balance 1500 Withdrew 200, balance 1300 Insufficient balance Invalid choice Goodbye
A do-while shows the menu at least once and repeats until the user chooses 4; the switch dispatches each choice. Checking every scanf() result keeps bad input from being treated as a number.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!