|
print("=== Control Flow Demo ===");
|
|
print("");
|
|
|
|
print("--- If Statement ---");
|
|
x = 10;
|
|
if (x > 5) {
|
|
print("x is greater than 5");
|
|
}
|
|
|
|
print("");
|
|
print("--- If-Else Statement ---");
|
|
y = 3;
|
|
if (y > 5) {
|
|
print("y is greater than 5");
|
|
} else {
|
|
print("y is not greater than 5");
|
|
}
|
|
|
|
print("");
|
|
print("--- If-Else If-Else Chain ---");
|
|
score = 85;
|
|
print("Score:", score);
|
|
if (score >= 90) {
|
|
print("Grade: A");
|
|
} else {
|
|
if (score >= 80) {
|
|
print("Grade: B");
|
|
} else {
|
|
if (score >= 70) {
|
|
print("Grade: C");
|
|
} else {
|
|
if (score >= 60) {
|
|
print("Grade: D");
|
|
} else {
|
|
print("Grade: F");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
print("");
|
|
print("--- Nested If ---");
|
|
a = 10;
|
|
b = 20;
|
|
if (a > 0) {
|
|
if (b > 0) {
|
|
print("Both a and b are positive");
|
|
}
|
|
}
|
|
|
|
print("");
|
|
print("--- While Loop ---");
|
|
print("Counting from 1 to 5:");
|
|
i = 1;
|
|
while (i <= 5) {
|
|
print(" i =", i);
|
|
i++;
|
|
}
|
|
|
|
print("");
|
|
print("--- While with Break Condition ---");
|
|
sum = 0;
|
|
n = 1;
|
|
while (n <= 100) {
|
|
sum += n;
|
|
if (sum > 50) {
|
|
print("Sum exceeded 50 at n =", n);
|
|
print("Final sum:", sum);
|
|
n = 101;
|
|
}
|
|
n++;
|
|
}
|
|
|
|
print("");
|
|
print("--- For Loop ---");
|
|
print("For loop 0 to 4:");
|
|
for (i = 0; i < 5; i++) {
|
|
print(" iteration", i);
|
|
}
|
|
|
|
print("");
|
|
print("--- For Loop with Step ---");
|
|
print("Counting by 2s:");
|
|
for (i = 0; i <= 10; i += 2) {
|
|
print(" i =", i);
|
|
}
|
|
|
|
print("");
|
|
print("--- Nested Loops ---");
|
|
print("Multiplication table (3x3):");
|
|
for (i = 1; i <= 3; i++) {
|
|
row = "";
|
|
for (j = 1; j <= 3; j++) {
|
|
row += str(i * j);
|
|
if (j < 3) {
|
|
row += "\t";
|
|
}
|
|
}
|
|
print(row);
|
|
}
|
|
|
|
print("");
|
|
print("--- Loop with Array ---");
|
|
colors = {"red", "green", "blue", "yellow"};
|
|
print("Colors:");
|
|
for (i = 0; i < len(colors); i++) {
|
|
print(" " + str(i) + ":", colors[i]);
|
|
}
|
|
|
|
print("");
|
|
print("--- Countdown ---");
|
|
print("Countdown:");
|
|
for (i = 5; i >= 1; i--) {
|
|
print(" ", i);
|
|
}
|
|
print(" Blast off!");
|
|
|
|
print("");
|
|
print("--- While True Pattern ---");
|
|
attempts = 0;
|
|
maxAttempts = 5;
|
|
while (1) {
|
|
attempts++;
|
|
print("Attempt", attempts);
|
|
if (attempts >= maxAttempts) {
|
|
print("Max attempts reached");
|
|
break;
|
|
}
|
|
}
|
|
|
|
print("");
|
|
print("--- Complex Condition ---");
|
|
age = 25;
|
|
hasLicense = 1;
|
|
if (age >= 18 && hasLicense) {
|
|
print("Can drive");
|
|
}
|
|
|
|
isMember = 0;
|
|
hasDiscount = 1;
|
|
if (isMember || hasDiscount) {
|
|
print("Eligible for discount");
|
|
}
|