Control Flow in Programming Languages

It’s like a rollercoaster ride for your code, but without all the screaming and vomiting (hopefully).

Control flow refers to how instructions are executed in a program based on certain conditions or decisions made by the developer. This is where things get interesting! Instead of just blindly executing every line of code from top to bottom like some mindless drone, we can make our programs do cool stuff like loops and conditional statements.

To begin, loops. Loops are like a never-ending cycle that repeats instructions over and over again until a certain condition is met or an exit statement is encountered. In programming terms, this is called iteration. There are two main types of loops: for loops and while loops.

For loops are great when you know exactly how many times you want to execute something. For example, let’s say we have an array with ten numbers in it and we want to add them all up. We can use a for loop like this:

// This script uses a for loop to iterate through an array and add all of its elements together.

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Declares an array with 10 numbers
let sum = 0; // Declares a variable to store the sum of the array elements, initialized to 0

for (let i = 0; i < arr.length; i++) { // Starts a for loop, with i as the loop counter, starting at 0 and ending at the length of the array
    sum += arr[i]; // Adds the current element of the array to the sum variable
}

console.log(sum); // Outputs the final sum of all the array elements, which should be 55

In this example, we’re using a for loop to iterate through the array and add each number to our `sum` variable. We start at index 0 (`i = 0`) and continue until we reach the end of the array (`i < arr.length`). The third part of the for statement is optional, but it's a good idea to use it if you want to modify your loop counter or do something else after each iteration. Now while loops. While loops are great when we don't know exactly how many times we need to execute something. For example, let's say we have an input that keeps asking the user for a number until they enter 0. We can use a while loop like this:

// Initialize variable to store user input
let num = null;

// Use a while loop to continuously ask for input until user enters 0
while (num !== 0) {
    // Prompt user for input and store it in the num variable
    num = prompt("Enter a number or press 'enter' to quit");

    // Check for empty input and non-numeric values
    if (num === "" || isNaN(num)) {
        // If input is invalid, log a message and continue to the next iteration
        console.log("Invalid input, please try again.");
        continue; // Go back to the beginning of the loop
    } else {
        // If input is valid, convert it to an integer and log it
        num = parseInt(num); // Convert string input to integer
        console.log(`You entered: ${num}`);
    }
}

// Once user enters 0, log a goodbye message
console.log("Goodbye!");

In this example, we’re using a while loop to keep asking the user for input until they enter 0 or press ‘enter’. We check if their input is empty or not numeric and handle those cases accordingly (by displaying an error message and going back to the beginning of the loop). If everything checks out, we convert their string input to an integer and log it to the console.

Now conditional statements also known as if-else statements or decision making structures. These are like forks in the road that allow us to make decisions based on certain conditions being met. There are two main types of conditional statements: if statements and switch statements (which we won’t cover here).

If statements are great when you want to execute one block of code or another depending on a condition. For example, let’s say we have an input that asks the user for their age and we want to display different messages based on whether they’re under 18 or over 65:

// This script prompts the user to enter their age and displays different messages based on their age.

let age = prompt("Enter your age"); // Prompts the user to enter their age and stores the input in the variable "age".

if (age < 18) { // Checks if the age is less than 18.
    console.log("You are too young to vote."); // If the age is less than 18, displays a message stating that the user is too young to vote.
} else if (age >= 18 && age <= 64) { // Checks if the age is between 18 and 64 (inclusive).
    console.log("You can vote, but you're not old enough for a senior discount yet."); // If the age is between 18 and 64, displays a message stating that the user can vote but is not old enough for a senior discount.
} else { // If the age is not less than 18 or between 18 and 64, it must be greater than 64.
    console.log("Congratulations! You've reached retirement age!"); // Displays a message congratulating the user for reaching retirement age.
}

In this example, we’re using an if statement to check whether the user is under 18 or over 65. If they are under 18, we display a message saying that they can’t vote yet. If they are between 18 and 64 (inclusive), we display a message saying that they can vote but aren’t old enough for a senior discount yet. Finally, if they are over 65, we congratulate them on reaching retirement age!

And there you have it the basics of control flow in programming languages! Remember to keep your code clean and readable by following style guides (like PEP8) and using comments sparingly but effectively.

SICORPS