From 3f86cfd92b167fd0b65e1cba31660cd0f0991c04 Mon Sep 17 00:00:00 2001 From: genga Date: Mon, 13 Apr 2026 20:22:55 +0300 Subject: [PATCH] docs: add control flow documentation for C4 --- docs/language/control_flow.md | 676 ++++++++++++++++++++++++++++++++++ 1 file changed, 676 insertions(+) create mode 100644 docs/language/control_flow.md diff --git a/docs/language/control_flow.md b/docs/language/control_flow.md new file mode 100644 index 0000000..8970c05 --- /dev/null +++ b/docs/language/control_flow.md @@ -0,0 +1,676 @@ +# Control Flow and Iteration +Control flow refers to the order in which statements/code blocks and instructions are executed in a program. +It helps determine how the program executes depending on certain conditions and logic. +Control flow helps developers create dynamic and flexible programs that can make decisions, repeat tasks and respond to various inputs. + +C4 supports familiar mathematical comparison conditions such as: +- Less than: `a < b` +- Greater than: `a > b` +- Equal to: `a == b` +- Less than or equal to: `a <= b` +- Greater than or equal to: `a >= b` +- Not equal to: `a != b` + +**These comparison condtions can be used to perform different actions for different decisions.** + +Methods of control flow management in a program: +- **Conditional Statements** - structures that allow a program to execute difference blocks of code based on whether a specified condition evaluates to `true` or `false`, eg `if statements, switch statements and ternary blocks`. +- **Loops** - structures that allow code block execution as long as the specified condition is `true`. +- **Flow control Keywords** - statements that interrupt the normal flow of a program. These are: `break, continue and return`. + +> [!NOTE] +> **In C4 control flow statements, code blocks start and end with a semicolon `:` instead of parenthesis `{}`.** + +
+
Figure 1: if statement example in C4
+ +```rust + if condition: // start of the code block + // statements to be executed + : // end of the code block +``` +
+ +
+
Figure 2: if statement example in C
+ +```rust + if (condition) { // start of the code block + // statements to be executed + } // end of the code block +``` +
+ +## Conditional Statements +Used in the decision-making process of a program. +Checks whether a condition is true and executes the corresponding code block. + +### if statement +Use this to specify the code block to be executed when the condition is `true`. +
+
Figure 3: Syntax
+ +```rust + if conditon: + // statements to be executed when the condition is true + : +``` +
+ +**The `if` keyword is written in lowercase letter. Uppercase letters(`If` or `IF`) will generate an error.** + +
+
Figure 4: Basic example
+ +```rust + if 50 < 100: + printf("50 is less than 100.\n") + : +``` +
+ +
+
Figure 5: Example using variables
+ +```rust + i32 x = 40 + i32 y = 20 + + if x > y: + printf("x is greater than y.\n") + : +``` + +
+ +
+ Explanation of the example in Figure 5 above. + +- _In the above example two variables are declared, `x` and `y`_. +- _Each variable is assigned a value_. +- _The two values are compared in the `if condition` check to determine if `x` is greater than(`>`) `y`_. +- _Values of `x` and `y` are `40` and `20` respecitively, since `40` is greater than `20`, the condition is `true` and the string `"x is greater than y"` is printed_. +
+ +### else statement +The `else` statement is used to specify the code block to be executed when the `if` condition is `false`. +
+
Figure 6: Syntax
+ +```rust + if condition: + // statements to be executed when the condition is true + : + else: + // statements to be executed when the condition is false + : +``` +
+ + +
+
Figure 7: if..else example:
+ +```rust + i32 x = 20 + i32 y = 40 + + if x > y: + printf("x is greater than y.\n") + : + else: + printf("x is less than y.\n") + : +``` +
+ +
+ Explanation of the example in Figure 7 above. + +- _Variable declaration and value assignment are done as in [Figure 5](#if_variable_code_example)_ +- _The values are compared in the `if condition` to determine whether `x` is greater than `y`._ +- _The values of `x` and `y` are `20` and `40` respectively._ +- _`20` is less than `40`, the `if condition` returns `false`._ +- _The first code block is skipped and the else block is executed priniting the string `"x is less than y"`._ +
+ +### elif statement +The `elif` statement allows multiple conditions to be checked sequentially. If the first condition is `false`, the program checks the next condition, and so on. If none of the conditions are `true`, the `else` block is executed. + +
+
Figure 8: Syntax
+ +```rust + if condition1: + // statements to be executed when the condition1 is true + : + elif condition2: + // statements to be executed when the condition2 is true + : + else: + // statements to be executed when the condition is false + : +``` +
+ + +
+
Figure 9: if...elif...else example
+ +```rust + i32 hour_of_day = 22 + + if hour_of_day < 12: + printf("Good morning.") + : + elif hour_of_day < 20: + printf("Good afternoon") + : + else: + printf("Good evening.") + : +``` +
+ +
+ Figure 9 explanation. + +- _The `hour_of_day` variable is greater than `10` meaning the first condition is `false`._ +- _In the second condition, the `elif` statement is `false` since the `hour_of_day` variable is less than `20`._ +- _Both conditions are `false`, the else block is evaluated and `"Good evening."` is printed on the screen._ +
+ +### Ternary operator +A ternary operator is a shorthand `if...else` statement with three operands. +The ternary operator returns a value based on a condition: if the condition is true, it returns the first value; otherwise it returns the second value. It can be used to replace multiple lines of code with a single line, it is often used to replace **simple `if...else` statements**. + + +
+
Figure 10: Ternary Syntax
+ +```rust + variable = condition ? expressionTrue : expressionFalse +``` +
+ + +
+
Figure 11: Ternary Example Code
+ +```rust + i32 x = 20 + + hour_of_day < 40 ? printf("x is less than 40") : printf("x is greater than 40") +``` +
+ +> [!NOTE] +> **A ternary operator is appropriate for simple, for multiple `if..else` conditions, a `switch` statement is appropriate.** + +### Switch statement +A control-flow structure that lets you compare a single value against multiple conditions. It replaces long chains of `if..else` statements and makes branching logic easier to read. **It is best used when many conditions depend on the same variable**. + +
+
Figure 12: Switch Syntax
+ +```c + switch expression: + case x: + // code block + break + : + case y: + //code block + : + default: + //code block + : + : +``` +
+ +> [!NOTE] +> A `switch expression` is evaluated once. +> +> The value of the `expression` is compared to the value of each `case`, if `true`, the associated block of code is executed. +> +> The `break` statement prevents further code execution within the `switch block`. +> +> The `default` statement is optional, it specifies code that run when there is no **case match**. + +
+
Figure 13: Switch Example
+ +```c + i32 day_of_week = 4; + + switch day_of_week: + case 1: + printf("Monday") + break + : + case 2: + printf("Tuesday") + break + : + case 3: + printf("Wednesday") + break + : + case 4: + printf("Thursday") + break + : + case 5: + printf("Friday") + break + : + case 6: + printf("Saturday") + break + : + case 7: + printf("Sunday") + break + : + : +``` +
+ +## Loops/Iterative Statement +A loop/iterative statement is used to repeat a block of code multiple times, tasks are performed repeatedly based on conditions. + +### While Loop +A loop that repeats a code block as long a the specified condition is `true`. + +
+
Figure 14: While Loop Syntax
+ +```c + while condition: + // code block to be executed + : +``` +
+ +
+
Figure 15: While Loop Example
The loop runs repeatedly as long as the variable(`index`) is less than 5
+ +```rust + i32 index = 0 + + while index < 5: + printf("%d\n", index) + index++ + : +``` +
+ +> [!NOTE] +> Remember to increase the variable used in the condition(`index++`) otherwise the loop execution never stops. + +
+
+ Figure 16: While Loop Countdown Example
This example counts down from 3 to 1 and prints `"Happy New Year!!"` at the end. +
+ +```rust + i32 countdown = 3 + + while countdown > 0: + printf("%d\n", countdown) + countdown-- + : + + printf("Happy New Year!!\n") +``` +
+ +
+
+ Figure 17: While Loop With False Condition
An example to showcase a loop with a `false` condition at the start, it prevents the inner code block from being executed. +
+ +```rust + i32 count = 10 + + while count < 5: + printf("This will never be printed\n") + count++ + : + +``` +
+ +> [!NOTE] +> A `while loop` may never run if the condition is `false` from the start. + +### Do..While Loop +A `while loop` variant that executes a code block once before checking if the condition is `true`. If the condtion is `true` the code block is executed repeatedly. + +
+
Figure 18: Do While Loop Syntax
+ +```c + do: + // code block to be executed + : + while condition +``` +
+ +
+
Figure 19: Do While Loop Example
The loop executes at least once even if the condition is `false`, the code is executed before the condition is tested.
+ +```c + i32 i = 0 + + do: + printf("%d\n", i) + i++ + : + while i < 5 +``` +
+ +> [!NOTE] +> Remember to increase the variable used in the condition(`i++`) otherwise the loop execution never stops. +> +> A practical example of the `do..while loop` is fetching user input. + +
+
Figure 20: Do While Loop Practical Example
+ +```c + i32 number + + do: + printf("Enter a positive number: ") + scanf("%d", &number) + : + while number > 0 +``` +
+ +### For Loop +A `loop` that is repeated a fixed number of times for each item in a sequence. + +
+
Figure 21: For Loop Syntax
+ Expression 1 is executed before the code block is executed.
+ Expression 2 defines the condition for executing the code block.
+ Expression 3 is executed after the code block is executed.
+
+ + +```c + for expression1; expression2; expression3: + //code block to be executed + : +``` +
+ +
+
Figure 22: For Loop Example
Print the numbers within the range of 0-5.
+ +```c + i32 i + + for i = 0; i < 5; i++: + printf("%d\n", i) + : +``` +
+ +
+ Figure 22 explained + +- The first statement set the variable `i` to `0` before the loop starts. +- The second statement sets the condition by which the loop is run: `i < 5`. +- The third statement increases the value of `i` each time the code block within the loop has been executed: `i++` +
+ + +### Loop +A `loop` that repeats execution of a block of code infinitely till it encounters a `break` statement. + +
+
Figure 23: Infinite Loop Syntax
+ +```c + loop: + //code block to be executed + : +``` +
+ +
+
Figure 24: Infinite Loop Example
The loop runs repeatedly.
+ +```c + loop: + printf("Infinite loop.\n") + : + + // The above code is similar to. + while true: + printf("Infinite loop.\n") + : +``` +
+ +## Nested Condtionals and Loops +`Nested conditionals` are conditional statements placed within other conditional statements. +`Nested loops` are loops placed within other loops. + +### Nested Conditionals +
+
Figure 25: Nested Conditional Syntax
+ +```rust + if condition1: + //code block to be executed if condition1 is true + if condition2: + //code block to be executed if condition2 is true + : + : +``` +
+ +
+
Figure 26: Nested Conditional Example
+ +```rust + i32 x = 15 + i32 y = 25 + + if x > 10: + printf("x is greater than 10\n") + + // Nested if + if y > 20: + printf("y is also greater than 20\n") + : + : +``` + +**Results:** `"x is greater than 10"` and `"y is also greater than 20"` +
+ +
+
Figure 27: Nested Conditional Example 2
+ +```rust + i32 age = 20 + bool is_citizen = true + + if age >= 18: + printf("Old enough to vote.\n") + + // Nested if + if is_citizen: + printf("A citizen is eligible to vote.") + : + else: + printf("You must be a citizen to be eligible for voting.\n") + : + : + else: + printf("Not old enough to vote.\n") + : +``` + +**Results:** `"Old enough to vote."` and `"A citizen is eligible to vote"` +
+ +> [!NOTE] +> You can nest many `if statements`, it is preferable to avoid such practices as it makes the code deeply nested and complicated to read. +> +> `Nested if` is often used together with `else` and `elif` for more complex decision-making. + +### Nested loops + + +
+
Figure 28: Nested Loop Example
+ +```c + i32 i = 0 + i32 j = 0 + + // Outer loop + + for i = 1; i <= 2; ++i: + printf("Outer: %d\n", i) // Executes 2 times + + // Inner loop + for j = 1; j <= 3; ++j: + printf(" Inner: %d\n", j) // Executes 6 times (2 * 3) + : + : + +``` +
+ +## Flow Control Keywords +### Break +As used in [Figure 13](#switch_example), this is a `jump out` statement. It immediately exits the `loop` or `switch` statement. + +
+
Figure 29: Break Statement Example
+ +```c + i32 i = 0 + + for i = 0; i < 10; i++: + + if i == 4: + break + : + + printf("%d\n", i) + : + +``` + +> [!NOTE] +> The `break` statement exits the loop once the value of `i` is `4`, it does not matter whether the condition of the loop is still `true` or `false`. +
+ +### Continue +The `continue` statement skips the current loop iteration and moves to the next. + +
+
Figure 30: Break Statement Example
+ +```c + i32 i = 0 + + for i = 0; i < 10; i++: + // The value of 4 is not printed + if i == 4: + continue + : + + printf("%d\n", i) + : + +``` + +
+ +### Combining Break and Continue Statements + +
+
Figure 31: Break and Continue Statement Example
+ +```c + i32 i = 0 + + for i = 0; i < 6; i++: + + if i == 2: + continue + : + + if i == 4: + break + : + + printf("%d\n", i) + : + +``` + +
+ + +## Logical Operators in Conditional Statements +`Logical operators` are symbols or keywords used to connect two or more expressions, resulting in a `boolean` value. + +Examples of `logical operators` in C4: +- `&&/and`(AND)- all conditions must be `true`. +- `||/or`(OR) - at least one condition must be `true`. +- `!/not`(NOT)- reverses/negates a conditon. + + +
+
Figure 32: Logical Operator Example
+ +```rust + i32 a = 200 + i32 b = 33 + i32 c = 500 + + // AND Example + if a > b && c > a: + printf("Both conditions are true\n") + : + + if a > b and c > a: + printf("Both conditions are true\n") + : + + // OR Example + if a > b || a > c: + printf("At least one condition is true\n") + : + + + if a > b or a > c: + printf("At least one condition is true\n") + : + + // NOT Example + if !(a > c): + printf("a is NOT greater than c\n") + : + + + if not (a > c): + printf("a is NOT greater than c\n") + : + +``` + +