Learn D with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
D Counter and Theme Toggle
import std.stdio;
int count = 0;
bool isDark = false;
void updateUI() {
writeln("Counter: ", count);
writeln("Theme: ", isDark ? "Dark" : "Light");
}
void increment() {
count += 1;
updateUI();
}
void decrement() {
count -= 1;
updateUI();
}
void reset() {
count = 0;
updateUI();
}
void toggleTheme() {
isDark = !isDark;
updateUI();
}
// Simulate actions
updateUI();
increment();
increment();
toggleTheme();
decrement();
reset();
Demonstrates a simple counter with theme toggling using D variables and console output.
2
D Simple Addition
import std.stdio;
void main() {
int a = 10;
int b = 20;
int sum = a + b;
writeln("Sum: ", sum);
}
Adds two numbers and prints the result.
3
D Factorial
import std.stdio;
int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
void main() {
writeln("Factorial 5: ", factorial(5));
}
Calculates factorial recursively.
4
D Fibonacci Sequence
import std.stdio;
int fib(int n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
void main() {
foreach(i; 0 .. 10)
writeln(fib(i));
}
Generates first 10 Fibonacci numbers.
5
D Max of Two Numbers
import std.stdio;
void main() {
int a = 10, b = 20;
int max = a > b ? a : b;
writeln("Max: ", max);
}
Finds the maximum of two numbers.
6
D Array Sum
import std.stdio;
void main() {
int[] arr = [1,2,3,4,5];
int sum = 0;
foreach(x; arr)
sum += x;
writeln("Sum: ", sum);
}
Sums elements of an array.
7
D Even Numbers Filter
import std.stdio;
void main() {
int[] arr = [1,2,3,4,5];
foreach(x; arr)
if(x % 2 == 0)
writeln(x);
}
Prints even numbers from an array.
8
D Conditional Counter Increment
import std.stdio;
void main() {
int count = 3;
if(count < 5)
count++;
writeln("Count: ", count);
}
Increment counter only if less than 5.
9
D Resettable Counter
import std.stdio;
void main() {
int count = 0;
count += 1;
count += 1;
writeln("Count: ", count);
count = 0;
writeln("Count: ", count);
}
Counter that increments and can be reset.
10
D Theme Toggle Only
import std.stdio;
void main() {
bool isDark = false;
writeln("Theme: ", isDark ? "Dark" : "Light");
isDark = !isDark;
writeln("Theme: ", isDark ? "Dark" : "Light");
isDark = !isDark;
writeln("Theme: ", isDark ? "Dark" : "Light");
}
Toggles theme multiple times.