C++ Program For Atm Machine
Creating an ATM machine program in C++ is an excellent way to practice fundamental programming concepts like user input, conditional statements, and loops. In this article, you will learn how to build a console-based ATM simulation that handles basic banking operations.
Problem Statement
Banks require robust systems to manage customer accounts, allowing users to perform operations like deposits, withdrawals, and balance inquiries securely and efficiently. Simulating this functionality helps in understanding real-world application logic and user interaction within a console environment.
Background & Knowledge Prerequisites
To effectively follow this tutorial, you should have a basic understanding of:
- C++ Syntax: How to declare variables, use basic operators, and write simple expressions.
- Data Types: Familiarity with
intfor integers anddoubleorfloatfor decimal numbers. - Conditional Statements: Using
if,else if, andelsefor decision-making. - Loops: Understanding
whileordo-whileloops for repetitive tasks. - Input/Output: Using
coutfor printing andcinfor reading user input.
Use Cases or Case Studies
ATM simulations serve various practical and educational purposes:
- Learning Programming Fundamentals: Ideal for beginners to apply concepts like user input, control flow, and basic arithmetic operations in a practical context.
- Rapid Prototyping: Developers can quickly prototype backend logic for financial transactions before integrating with complex database systems or graphical interfaces.
- Educational Tools: Used in computer science courses to demonstrate system design principles and object-oriented programming (OOP) concepts for more advanced versions.
- Testing User Interfaces: Even for console-based applications, it helps in understanding how users might interact with a menu-driven system.
- Basic Financial Management: A simple version can be adapted for personal budget tracking or managing small accounts.
Solution Approaches
We will explore a few approaches, starting with a basic functional program and progressively adding more features for interactivity and security.
Approach 1: Basic Transaction Flow
This approach demonstrates the core logic of an ATM, allowing a single sequence of deposit, withdrawal, and balance check operations without a looping menu.
One-line summary: Perform sequential deposit, withdrawal, and balance check operations.
// Basic ATM Transaction Flow
#include <iostream>
using namespace std;
int main() {
// Step 1: Initialize account balance
double balance = 1000.00; // Starting balance
cout << "Welcome to the Simple ATM!" << endl;
cout << "Initial Balance: $" << balance << endl;
// Step 2: Simulate a deposit
double depositAmount = 500.00;
balance += depositAmount; // Add deposit to balance
cout << "Depositing $" << depositAmount << endl;
cout << "Current Balance after deposit: $" << balance << endl;
// Step 3: Simulate a withdrawal
double withdrawAmount = 200.00;
if (balance >= withdrawAmount) {
balance -= withdrawAmount; // Subtract withdrawal from balance
cout << "Withdrawing $" << withdrawAmount << endl;
cout << "Current Balance after withdrawal: $" << balance << endl;
} else {
cout << "Insufficient Balance for withdrawal of $" << withdrawAmount << endl;
}
// Step 4: Display final balance
cout << "Final Balance: $" << balance << endl;
return 0;
}
Sample Output:
Welcome to the Simple ATM!
Initial Balance: $1000
Depositing $500
Current Balance after deposit: $1500
Withdrawing $200
Current Balance after withdrawal: $1300
Final Balance: $1300
Stepwise Explanation:
- Initialize Balance: A
doublevariablebalanceis initialized to$1000.00to represent the customer's starting funds. - Display Initial Balance: The program prints a welcome message and the initial
balance. - Simulate Deposit: A
depositAmountof$500.00is added to thebalance, and the new balance is displayed. - Simulate Withdrawal: A
withdrawAmountof$200.00is attempted. Anifstatement checks if thebalanceis sufficient for the withdrawal. If yes, the amount is subtracted; otherwise, an "Insufficient Balance" message is shown. - Display Final Balance: The final
balanceafter all operations is printed.
Approach 2: Interactive Menu-Driven ATM
This approach enhances the ATM with an interactive menu, allowing the user to choose operations (deposit, withdraw, check balance, exit) repeatedly until they decide to quit. This utilizes a do-while loop and a switch statement.
One-line summary: Implement an interactive menu using a do-while loop and switch for multiple transactions.
// Interactive Menu-Driven ATM
#include <iostream> // For input/output operations
#include <limits> // For numeric_limits to clear cin buffer
using namespace std;
int main() {
double balance = 1000.00; // Starting balance
int choice; // User's menu choice
cout << "Welcome to the Interactive ATM!" << endl;
do {
// Step 1: Display the ATM menu
cout << "\\nATM Menu:" << endl;
cout << "1. Check Balance" << endl;
cout << "2. Deposit" << endl;
cout << "3. Withdraw" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
// Clear input buffer in case of invalid input (non-numeric)
if (cin.fail()) {
cout << "Invalid input. Please enter a number." << endl;
cin.clear(); // Clear the error flag
cin.ignore(numeric_limits<streamsize>::max(), '\\n'); // Discard invalid input
continue; // Skip to the next loop iteration
}
// Step 2: Process user's choice using a switch statement
switch (choice) {
case 1: // Check Balance
cout << "Your current balance is: $" << balance << endl;
break;
case 2: { // Deposit
double depositAmount;
cout << "Enter amount to deposit: $";
cin >> depositAmount;
if (depositAmount > 0) {
balance += depositAmount;
cout << "Deposit successful. New balance: $" << balance << endl;
} else {
cout << "Deposit amount must be positive." << endl;
}
break;
}
case 3: { // Withdraw
double withdrawAmount;
cout << "Enter amount to withdraw: $";
cin >> withdrawAmount;
if (withdrawAmount > 0) {
if (balance >= withdrawAmount) {
balance -= withdrawAmount;
cout << "Withdrawal successful. New balance: $" << balance << endl;
} else {
cout << "Insufficient balance." << endl;
}
} else {
cout << "Withdrawal amount must be positive." << endl;
}
break;
}
case 4: // Exit
cout << "Thank you for using the ATM. Goodbye!" << endl;
break;
default: // Invalid choice
cout << "Invalid choice. Please try again." << endl;
break;
}
} while (choice != 4); // Loop continues until user chooses to exit
return 0;
}
Sample Output (Interactive Session):
Welcome to the Interactive ATM!
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 1
Your current balance is: $1000
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 2
Enter amount to deposit: $250
Deposit successful. New balance: $1250
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 3
Enter amount to withdraw: $300
Withdrawal successful. New balance: $950
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 5
Invalid choice. Please try again.
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 4
Thank you for using the ATM. Goodbye!
Stepwise Explanation:
- Initialize Balance and Choice:
balanceis set, andchoicestores the user's menu selection. do-whileLoop: The program enters ado-whileloop, ensuring the menu is displayed at least once. The loop continues as long aschoiceis not4(Exit).- Display Menu: Inside the loop, a clear menu of options is printed to the console.
- Get User Input:
cin >> choicereads the user's selection. Input validation is included to handle non-numeric inputs. switchStatement: Aswitchstatement processes thechoice:- Case 1 (Check Balance): Displays the current
balance.
- Case 1 (Check Balance): Displays the current
depositAmount. If positive, it's added to balance.withdrawAmount. If positive and balance is sufficient, it's subtracted.while condition.choice outside the 1-4 range.Approach 3: Adding PIN Verification
Building upon the interactive ATM, this approach adds a simple Personal Identification Number (PIN) verification step at the beginning, restricting access to authorized users.
One-line summary: Incorporate a PIN verification before granting access to the ATM menu.
// ATM with PIN Verification
#include <iostream>
#include <limits> // For numeric_limits
using namespace std;
int main() {
// Step 1: Set a predefined PIN and initial balance
const int CORRECT_PIN = 1234;
int enteredPin;
double balance = 1500.00; // Starting balance
int choice;
cout << "Welcome to the Secure ATM!" << endl;
// Step 2: Request PIN from the user
cout << "Please enter your 4-digit PIN: ";
cin >> enteredPin;
// Clear input buffer in case of invalid input (non-numeric for PIN)
if (cin.fail()) {
cout << "Invalid input. Please enter a number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\\n');
return 1; // Exit program if initial PIN input is invalid
}
// Step 3: Validate the PIN
if (enteredPin != CORRECT_PIN) {
cout << "Incorrect PIN. Access Denied." << endl;
return 0; // Exit program if PIN is incorrect
}
cout << "PIN accepted. Access granted." << endl;
// Step 4: Proceed with the interactive menu (same as Approach 2)
do {
cout << "\\nATM Menu:" << endl;
cout << "1. Check Balance" << endl;
cout << "2. Deposit" << endl;
cout << "3. Withdraw" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
if (cin.fail()) {
cout << "Invalid input. Please enter a number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\\n');
continue;
}
switch (choice) {
case 1:
cout << "Your current balance is: $" << balance << endl;
break;
case 2: {
double depositAmount;
cout << "Enter amount to deposit: $";
cin >> depositAmount;
if (depositAmount > 0) {
balance += depositAmount;
cout << "Deposit successful. New balance: $" << balance << endl;
} else {
cout << "Deposit amount must be positive." << endl;
}
break;
}
case 3: {
double withdrawAmount;
cout << "Enter amount to withdraw: $";
cin >> withdrawAmount;
if (withdrawAmount > 0) {
if (balance >= withdrawAmount) {
balance -= withdrawAmount;
cout << "Withdrawal successful. New balance: $" << balance << endl;
} else {
cout << "Insufficient balance." << endl;
}
} else {
cout << "Withdrawal amount must be positive." << endl;
}
break;
}
case 4:
cout << "Thank you for using the ATM. Goodbye!" << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
break;
}
} while (choice != 4);
return 0;
}
Sample Output (Correct PIN):
Welcome to the Secure ATM!
Please enter your 4-digit PIN: 1234
PIN accepted. Access granted.
ATM Menu:
1. Check Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 1
Your current balance is: $1500
... (rest of the interactive session as in Approach 2)
Sample Output (Incorrect PIN):
Welcome to the Secure ATM!
Please enter your 4-digit PIN: 5678
Incorrect PIN. Access Denied.
Stepwise Explanation:
- Define PIN and Balance: A
const int CORRECT_PINis set.enteredPinwill store the user's input. - Request PIN: The program prompts the user to enter their PIN.
- Validate PIN: An
ifstatement comparesenteredPinwithCORRECT_PIN.- If they don't match, an "Incorrect PIN" message is displayed, and the program exits immediately using
return 0;.
- If they don't match, an "Incorrect PIN" message is displayed, and the program exits immediately using
- Interactive Menu: The rest of the program functions exactly like Approach 2, providing the menu-driven banking operations.
Conclusion
Developing an ATM machine program in C++ is a foundational exercise that reinforces several core programming concepts. From basic sequential operations to interactive menu systems and security features like PIN verification, these examples demonstrate how to structure a program to handle user input, make decisions, and repeat actions.
Summary
Key takeaways from building a C++ ATM program:
- Variables and Data Types: Used
doubleforbalanceandintforchoiceandPIN. - Input/Output:
cinandcoutare essential for user interaction. - Conditional Logic:
if-elsestatements handle conditions like insufficient balance and PIN validation. - Looping: A
do-whileloop creates a persistent, interactive menu system. - Selection Control: A
switchstatement efficiently manages different menu options. - Basic Error Handling: Included simple checks for invalid numeric input using
cin.fail()andnumeric_limits.