In this tutorial, we will create a simple calculator using Dart programming. A calculator is a fundamental tool that performs arithmetic operations such as addition, subtraction, multiplication, and division. Learning to build a calculator is important because it helps beginners understand basic programming concepts like user input, data types, and control flow. You'll find calculators used in various applications, from simple mobile apps to complex software systems.
What is a Simple Calculator?
A simple calculator is a program that takes two numbers and an arithmetic operator from the user, performs the specified operation, and returns the result. This concept serves as an excellent starting point for beginners to grasp the basics of programming logic, user input handling, and function creation.
Syntax
// Basic structure of a simple calculator in Dart
void main() {
// Declare variables for numbers and operator
double num1, num2, result;
String operator;
// Read user inputs
// Perform calculation based on the operator
// Print the result
}
How It Works
- User Input: The program prompts the user to enter two numbers and an operator (e.g., +, -, *, /).
- Operation Selection: It checks which arithmetic operation the user wants to perform.
- Computation: Based on the operator, it performs the calculation.
- Output: Finally, it displays the result to the user.
Example 1: Basic Usage
import 'dart:io'; // Importing library for input/output
void main() {
// Prompt user for the first number
print('Enter the first number:');
double num1 = double.parse(stdin.readLineSync()!); // Read and parse input
// Prompt user for the second number
print('Enter the second number:');
double num2 = double.parse(stdin.readLineSync()!); // Read and parse input
// Perform addition
double result = num1 + num2; // Calculate the sum
// Print the result
print('The result of addition is: $result'); // Output the result
}
Output:
Enter the first number:
5
Enter the second number:
10
The result of addition is: 15.0
Explanation: The program prompts the user for two numbers, adds them together, and prints the result.
Example 2: Intermediate Usage with Variations
import 'dart:io';
void main() {
// Declare variables
double num1, num2, result;
String operator;
// Read user inputs
print('Enter the first number:');
num1 = double.parse(stdin.readLineSync()!);
print('Enter the second number:');
num2 = double.parse(stdin.readLineSync()!);
// Read operator
print('Enter an operator (+, -, *, /):');
operator = stdin.readLineSync()!;
// Perform calculation based on operator
if (operator == '+') {
result = num1 + num2; // Addition
} else if (operator == '-') {
result = num1 - num2; // Subtraction
} else if (operator == '*') {
result = num1 * num2; // Multiplication
} else if (operator == '/') {
result = num1 / num2; // Division
} else {
print('Invalid operator!'); // Error message for invalid operator
return; // Exit the program
}
// Print the result
print('The result is: $result');
}
Output:
Enter the first number:
6
Enter the second number:
3
Enter an operator (+, -, *, /):
*
The result is: 18.0
Explanation: This example allows the user to choose between four arithmetic operations and displays the result accordingly.
Example 3: Real-World Application
import 'dart:io';
void main() {
// Create a function to perform calculations
double calculate(double num1, double num2, String operator) {
switch (operator) {
case '+':
return num1 + num2; // Return sum
case '-':
return num1 - num2; // Return difference
case '*':
return num1 * num2; // Return product
case '/':
return num1 / num2; // Return quotient
default:
throw Exception('Invalid operator!'); // Error for invalid operator
}
}
// Read user inputs
print('Enter the first number:');
double num1 = double.parse(stdin.readLineSync()!);
print('Enter the second number:');
double num2 = double.parse(stdin.readLineSync()!);
print('Enter an operator (+, -, *, /):');
String operator = stdin.readLineSync()!;
// Calculate and print result
try {
double result = calculate(num1, num2, operator); // Call the function
print('The result is: $result');
} catch (e) {
print(e); // Print error message if an exception occurs
}
}
Output:
Enter the first number:
8
Enter the second number:
4
Enter an operator (+, -, *, /):
/
The result is: 2.0
Explanation: This example demonstrates creating a function to encapsulate the calculation logic, making the code more reusable and organized.
Example 4: Edge Cases or Special Scenarios
import 'dart:io';
void main() {
print('Enter the first number:');
double num1 = double.parse(stdin.readLineSync()!);
print('Enter the second number:');
double num2 = double.parse(stdin.readLineSync()!);
print('Enter an operator (+, -, *, /):');
String operator = stdin.readLineSync()!;
// Check for division by zero
if (operator == '/' && num2 == 0) {
print('Error: Division by zero is not allowed!'); // Error message
} else {
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
print('Invalid operator!'); // Error message
return;
}
print('The result is: $result'); // Output the result
}
}
Output:
Enter the first number:
9
Enter the second number:
0
Enter an operator (+, -, *, /):
/
Error: Division by zero is not allowed!
Explanation: This program checks for division by zero and handles this special case, preventing runtime errors.
When to Use Simple Calculator in Dart
| Topic | Description |
|---|---|
| Learning Programming Basics | Great for beginners to understand user input and arithmetic operations. |
| Small-Scale Applications | Useful in apps that require basic computations without complex features. |
| Educational Tools | Can be used in educational software to teach basic math. |
Key Points
| Topic | Description |
|---|---|
| User Input Handling | Learn how to read and parse inputs from users. |
| Control Flow | Understand using if-else and switch statements for decision making. |
| Function Creation | Encapsulate logic in functions for better code organization. |
| Error Handling | Implement checks for special cases like division by zero. |
| Reusability | Write functions to make code modular and easy to maintain. |
| Practical Application | Real-world applications often begin with simple functionalities like a calculator. |
With this tutorial, you now have a solid foundation for building a simple calculator in Dart. Happy coding!