Part 2 of 7 · 4-minute read. My learning notes on the main programming paradigms, with Dart examples.
Concept
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.
Real-Life Analogy
Imagine you're teaching someone to make a sandwich:
- Get two slices of bread
- Spread butter on one slice
- Add cheese on the buttered slice
- Place the second slice on top
- Cut the sandwich diagonally
Each step modifies the state (the sandwich being built) until you reach the final result.
Dart Example
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:
- Initialize a sum variable
- Loop through each number
- Calculate the square
- Add it to the sum
Imperative Flow Diagram
╔══════════════════════════════════════════════════════════╗
║ 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.
Further Reading
Imperative Programming:
- Imperative vs Declarative Programming - Clear comparison
- Control Flow in Dart - Official guide
Algorithms and Control Flow:
- Introduction to Algorithms - Classic reference
- Big-O Notation - Algorithm complexity
Practice:
- LeetCode - Algorithm practice problems
- HackerRank - Coding challenges
Originally published at projekt.github.io/articles. I'm Srđan Ljuština — I build small, privacy-friendly apps at srdapp.rs. Find me on LinkedIn and GitHub.
Top comments (0)