⏱️ Quick 4-Minute Read
| Series Navigation: ← What Are Programming Paradigms? | Article 2 of 7 | Next: Object-Oriented Programming → |
About This Series
This article series represents my journey of learning and applying fundamental programming concepts to the Dart programming language. These are my detailed notes and insights from the learning process, which I hope will be valuable to others exploring similar topics.
Imperative programming is like following a recipe step-by-step. You give the computer explicit instructions about what to do and in what order, focusing on how to achieve a result.
Imagine you’re teaching someone to make a sandwich:
Each step modifies the state (the sandwich being built) until you reach the final result.
void main() {
// Imperative approach to calculate sum of squares
List<int> numbers = [1, 2, 3, 4, 5];
int sum = 0;
// Step-by-step instructions
for (int i = 0; i < numbers.length; i++) {
int square = numbers[i] * numbers[i];
sum = sum + square;
}
print('Sum of squares: $sum'); // Output: 55
}
In this example, we explicitly tell the computer to:
╔══════════════════════════════════════════════════════════╗
║ IMPERATIVE EXECUTION FLOW ║
╚══════════════════════════════════════════════════════════╝
START
│
▼
┌─────────────────────┐
│ INITIALIZE │
│ ───────────────── │
│ sum = 0 │
│ i = 0 │
│ numbers = [1..5] │
└──────────┬──────────┘
│
▼
┌──────────────┐
┌─────┤ CONDITION │
│ │ i < length? │
│ └──────┬───────┘
│ YES│ │NO
│ │ └─────────────┐
│ ▼ │
│ ┌──────────────┐ │
│ │ CALCULATE │ │
│ │ ────────── │ │
│ │ square = │ │
│ │ numbers[i]² │ │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ ADD │ │
│ │ ────────── │ │
│ │ sum = sum + │ │
│ │ square │ │
│ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ INCREMENT │ │
│ │ ────────── │ │
│ │ i = i + 1 │ │
│ └──────┬───────┘ │
│ │ │
└────────────┘ │
│
┌───────────────┘
▼
┌──────────────┐
│ OUTPUT │
│ ────────── │
│ Print result │
│ sum = 55 │
└──────────────┘
│
▼
END
Legend: Init | Decision | Compute | Update | Loop | Output
Imperative programming gives you explicit control over the execution flow, making it ideal for algorithms and scripts where you need precise control over how operations are performed. The trade-off is that you must specify every detail of the process, which can make code more verbose compared to other paradigms.
Imperative Programming:
Algorithms and Control Flow:
Practice:
Srđan Ljuština - Software Developer & Technical Writer
| 🌐 Website | 💻 GitHub |
| Series Navigation: ← What Are Programming Paradigms? | Article 2 of 7 | Next: Object-Oriented Programming → |
Other Articles in This Series: