# Control Flow
## Boolean Expressions
Boolean expressions are statements that evaluate to either true or false. They are commonly used in programming to make decisions and control the flow of a program. Boolean expressions use boolean operators. Boolean operators are different from arithmetic operators as they return boolean values while arithmetic operators return numeric values. The two categories of boolean operators are: comparative operators and logical operators.
### Comparative Operators
Comparative operators are used to compare values. Here are some common comparative operators:
#### Equalitly (==):
Compares if two values are equal.
#### Strict Equality (===)
The === operator in JavaScript is known as the strict equality operator. It compares two values for equality without performing type conversion. In other words, it not only checks if the values are equal but also ensures that their data types are the same.
- Example: `5 === 5` is true because both values are the same (number).
- Example: `'5' === 5` is false because the values are the same, but their data types are different (string and number).
#### Inequality (!=)
Checks if two values are not equal.
#### Strict Inequality
The !== operator is the strict inequality operator in JavaScript. It is the opposite of === and checks if two values are not equal without performing type conversion.
- Example: 5 !== 5 is false because both values are the same (number).
- Example: '5' !== 5 is true because the values are not the same, or they have different data types.
#### Greater than (>) and Less than (<)
These operators compare if one value is greater or less than another.
- Example: x > y is true if x is greater than y.
#### Greater than or equal to (>=) and Less than or equal to (<=)
These operators compare if one value is greater or equal to, or less than or equal to, another value.
- Example: x >= y is true if x is greater than OR equal to y.
### Logical Operators
Logical operators are used to combine multiple boolean expressions.
#### Logical AND (&&)
Truth Table:
| A | B | A && B |
| ----- | ----- | ------ |
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
The logical AND (&&) operator only returns true with both operands are true
#### Logical OR (||)
Truth Table:
| A | B | A \|\| B |
| ----- | ----- | -------- |
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
The logical OR (||) operator only returns false with both operands are false
#### Logical NOT (!)
Truth Table:
| A | !A |
| ----- | ----- |
| true | false |
| false | true |https://hackmd.io/7cKWQkhHQ6qj8KsIoDYMWQ#Logical-Operators
These operators allow you to create complex conditions and make decisions in your code based on the evaluation of boolean expressions.
#### Summary Video: [YouTube](https://www.youtube.com/watch?v=R8jAVrhzpl0&list=PL98qAXLA6afsQO62IkkidTHXmuL6k2rR6&index=6)
## Conditionals
A code segment is a collection of a few lines of code that performs a specific task or function. In JavaScript, you can create a code segment using curly braces {}. Here's how you do it:
```javascript=
// This is the start of a code segment
{
// You can have multiple lines of code here
let x = 5;
let y = 10;
let result = x + y;
console.log(result);
}
// This is the end of the code segment
```
In this example, the code segment is enclosed within curly braces. It contains the code to calculate the sum of x and y and then log the result. Code segments help keep related code together and make it easier to read and manage.
In computer programming, there may arise situations where you have to run a block of code among more than one alternatives.
In such situations, you can use the JavaScript conditional statements to create a program that can make decisions. In JavaScript, there are three forms of conditional statements.
1. if statement
2. if...else statement
3. if...else if...else statement
### if statement
The syntax of the if statement is:
```javascript=
if (condition) {
// the body of if
}
```
**NOTE: The code inside { } is the body of the if statement.**
The if statement evaluates the condition inside the parenthesis ().
If the condition is evaluated to true, the code inside the body of if **IS EXECUTED**

If the condition is evaluated to false, the code inside the body of if **IS SKIPPED**

### if...else statement
An if statement can have an optional else clause. The syntax of the if...else statement is:
```javascript=
if (condition) {
// block of code if condition is true
} else {
// block of code if condition is false
}
```
The if..else statement evaluates the condition inside the parenthesis.
**If the condition is evaluated to true:**
- The code inside the body of if is executed
- The code inside the body of else is skipped from execution

**If the condition is evaluated to false:**
- The code inside the body of else is executed
- The code inside the body of if is skipped from execution

### if...else if...else statement
The if...else statement is used to execute a block of code among two alternatives. However, if you need to make a choice between more than two alternatives, if...else if...else can be used.
The syntax of the if...else if...else statement is:
```javascript=
if (condition1) {
// code block 1
} else if (condition2){
// code block 2
} else {
// code block 3
}
```
* If condition1 evaluates to true, the code block 1 is executed.
* If condition1 evaluates to false, then condition2 is evaluated.
* If the condition2 is true, the code block 2 is executed.
* If the condition2 is false, the code block 3 is executed.

#### Demo Code: Conditionals
```javascript=
// Write a calculator program that performs addition, subtraction, division, multiplication and remainder. It should ask the user what operation they want to perform and then perform the calculation.
// Create your program's algorithm
// 1. Ask the user what operation they want to perform
// 2. If the user wants to add
// 2a. Ask for two numbers
// 2b. Add the two numbers
// 2c. Output the result
// 3. ELSE If the user wants to subtract
// 3a. Ask for two numbers
// 3b. Subtract the two numbers
// 3c. Output the result
// 4. ELSE If the user wants to multiply
// 4a. Ask for two numbers
// 4b. Multiple the two numbers
// 4c. Output the result
// 5. ELSE If the user wants to divide
// 5a. Ask for two numbers
// 5b. Divide the two numbers
// 5c. Output the result
// 5. ELSE If the user wants to calculate remainder
// 5a. Ask for two numbers
// 5b. Find the remained of the two numbers
// 5c. Output the result
// 6. ELSE output that is a not a valid operation
// Write your program
console.log("Addition, Subtract, Multiplicat, Division, Remainder\n");
// Get user input for the operation
let operation = prompt("What is your choice: ");
// Get user input for the first number
let num1 = parseFloat(prompt("\nEnter first number: "));
// Get user input for the second number
let num2 = parseFloat(prompt("\nEnter second number: "));
// Check if the operation is addition
if (operation === "addition") {
// Calculate the sum
let sum = num1 + num2;
// Output the addition result
console.log(`${num1} + ${num2} = ${sum}`);
// Check if the operation is subtraction
} else if (operation === "subtraction") {
// Calculate the difference
let difference = num1 - num2;
// Output the subtraction result
console.log(`\n${num1} - ${num2} = ${difference}`);
// Check if the operation is multiplication
} else if (operation === "multiplication") {
// Calculate the product
let product = num1 * num2;
// Output the multiplication result
console.log(`\n${num1} * ${num2} = ${product}`);
// Check if the operation is division
} else if (operation === "division") {
// Calculate the quotient
let quotient = num1 / num2;
// Output the division result
console.log(`\n${num1} / ${num2} = ${quotient}`);
// Check if the operation is remainder
} else if (operation === "remainder") {
// Calculate the remainder
let remainder = num1 % num2;
// Output the remainder result
console.log(`\n${num1} % ${num2} = ${remainder}`);
} else {
// Output a message for an invalid operation
console.log("Not a valid operation");
}
```
#### Summary Video: [YouTube](https://www.youtube.com/watch?v=M4IKd-GC9jw&list=PL98qAXLA6afsQO62IkkidTHXmuL6k2rR6&t=1s)
## Iteration
Iterative statements are also referred to as repetitive statements or loops. Iteration allows programmers to repeat lines of code for a set number of times or for as long as a condition is met.
In programming, loops are used to repeat a block of code.
## while Loops
while loops are used to repeat a block of code for as long as a condition is met
The syntax of the while loop is:
```javascript=
while (condition) {
// body of loop
}
```
A while loop evaluates the condition inside the parenthesis ().
- If the condition evaluates to true, the code inside the while loop is executed.
- The condition is evaluated again.
- This process continues until the condition is false.
When the condition evaluates to false, the loop stops.
### Demo Code: while Loop w/Increasing Counter
```javascript=
// PROGRAM DESCRIPTION
// This program simulates an age-related message loop. It starts with an age of 0
// and outputs messages indicating the current age and a reminder that drinking
// is illegal for individuals below 21. The loop continues until the age reaches 21,
// at which point it displays a message indicating that the person can now legally drink.
// PROGRAM ALGORITHM
// 1. Start with an age variable initialized to 0.
// 2. Enter a loop with the condition that the age is less than 21.
// a. Output the current age.
// b. Output a reminder that it's illegal to drink.
// c. Increment the age by 1 in each iteration.
// 3. After the loop, when the age reaches 21, display a message indicating that the person can now legally drink.
// 4. End the program.
// PROGRAM CODE
// Initialize: Start with an age of 0
let age = 0;
// Condition: Continue as long as age is less than 21
while (age < 21) {
// Output the current age
console.log("\nYou are currently", age, "years old");
// Remind that it's illegal to drink
console.log("IT IS ILLEGAL FOR YOU TO DRINK");
// Increment: Increase the age by 1 in each iteration
age++;
}
// Display a message after the loop when age is 21
console.log("\nYOU ARE 21 AND CAN DRINK");
```
### Demo Code: while Loop w/Decreasing Counter
```javascript=
// PROGRAM DESCRIPTION
// This program implements a countdown from 10 to 1, displaying each countdown value along with a newline.
// It concludes with a message wishing a "HAPPY NEW YEAR!" after the countdown.
// PROGRAM ALGORITHM
// 1. Initialize: Start with a countdown value of 10.
// 2. Enter a loop with the condition that the countdown is greater than 0.
// a. Output the current countdown value and a newline.
// b. Decrement: Decrease the countdown by 1 in each iteration.
// 3. After the loop completes, display a message saying "HAPPY NEW YEAR!"
// 4. End the program.
// PROGRAM CODE
// Initialize: Start with a countdown value of 10
let countdown = 10;
// Condition: Continue as long as countdown is greater than 0
while (countdown > 0) {
// Output the current countdown value and a newline
console.log(countdown, "\n");
// Decrement: Decrease the countdown by 1 in each iteration
countdown--;
}
// Display a message after the loop completes
console.log("HAPPY NEW YEAR!");
```
### Demo Code: while Loop w/Equality Check
```javascript=
// PROGRAM DESCRIPTION
// This program prompts the user to guess a secret word, which is initially set to "Apple".
// It provides feedback for each incorrect guess and continues prompting until the correct word is guessed.
// PROGRAM ALGORITHM
// 1. Initialize: Set the secret word to "Apple".
// 2. Display a message instructing the user to guess the secret word.
// 3. Get user input for the initial guess.
// 4. Enter a loop with the condition that the guess is incorrect (not equal to the secret word).
// a. Output a message indicating that the current guess is incorrect and prompt the user to try again.
// b. Get another guess from the user.
// 5. After the loop, display a message indicating that the user has guessed the word correctly.
// 6. End the program.
// PROGRAM CODE
// Initialize: Set the secret word to "Apple"
let secretWord = "Apple";
console.log("Eve ate this fruit. Guess what it is");
// Get user input for the initial guess
let userGuess = prompt("");
// Condition: Continue as long as the guess is incorrect
while (userGuess !== secretWord) {
// Output a message for an incorrect guess
console.log("\n", userGuess, "is not the word. Try again");
// Get another guess from the user
userGuess = prompt("");
}
// Display a message after the correct guess
console.log("You guessed correctly");
```
Summary Video: [YouTube](https://www.youtube.com/watch?v=RxMXNzHgGrY&list=PL98qAXLA6afsQO62IkkidTHXmuL6k2rR6)
## for Loops
for loops are used to repeat a block of code for a set number of times
The syntax of the for loop is:
```javascript=
for (initialExpression; condition; updateExpression) {
// for loop body
}
```
1. The `initialExpression` initializes and/or declares variables and executes only once.
2. The condition is evaluated.
3. If the condition is false, the for loop is terminated.
4. If the condition is true, the block of code inside of the for loop is executed.
5. The updateExpression updates the value of initialExpression when the condition is true.
6. The condition is evaluated again. Steps 2-5 continue until the condition is false.
### Demo Code: for Loop w/Increasing Counter
```javascript=
// PROGRAM DESCRIPTION
// This program utilizes a loop to iterate through grades starting from 9 up to and including 12.
// It outputs a message for each grade, and after the loop completes, it displays a graduation message.
// PROGRAM ALGORITHM
// 1. Enter a loop with:
// a. Initialize Expression: Start with grade 9
// b. Continuation Condition: Continue as long as grade is less than or equal to 12
// c. Increment exrpression: Increase the grade by 1 in each iteration
// d. Body: Output a message with the current grade
// 2. After the loop completes, display a graduation message.
// 3. End the program.
// PROGRAM CODE
// Initialize Expression: Start with grade 9
// Continuation Condition: Continue as long as grade is less than or equal to 12
// Increment exrpression: Increase the grade by 1 in each iteration
for (let grade = 9; grade <= 12; grade++) {
// Output a message with the current grade
console.log("You are in grade", grade, "!");
}
// Display a graduation message after the loop
console.log("Congratulations, you graduated!");
```
### Demo Code: for Loop w/Decreasing Counter
```javascript=
// PROGRAM DESCRIPTION
// This program uses a loop to perform a countdown from 10 to 1, logging each countdown value along with a newline character.
// After the loop completes, it prints a "HAPPY NEW YEAR!" message.
// PROGRAM ALGORITHM
// 1. Enter a loop with:.
// a. Body of the loop: Log the current countdown value and a newline character.
// b. Initialize expression: Setting up the countdown variable with an initial value of 10
// c. Continuation condition: Loop continues as long as countdown is greater than 0
// d. Increment expression: Decreasing the countdown variable by 1 in each iteration
// 2. After the loop completes, print a "HAPPY NEW YEAR!" message.
// 3. End the program.
// Initialize expression: Setting up the countdown variable with an initial value of 10
// Continuation condition: Loop continues as long as countdown is greater than 0
// Increment expression: Decreasing the countdown variable by 1 in each iteration
for (let countdown = 10; countdown > 0; countdown--) {
// Body of the loop: Logging the current countdown value and a newline character
console.log(countdown, "\n");
}
// Code outside the loop: Printing a message after the loop completes
console.log("HAPPY NEW YEAR!");
```
#### Summary Video: [YouTube](https://www.youtube.com/watch?v=Y32i2I-Pcc8&list=PL98qAXLA6afsQO62IkkidTHXmuL6k2rR6)
## Software Engineering: Program Purpose & Algorithm
### Program Purpose: Defining the Goal
The purpose of a computer program is its primary objective or goal. It defines what the program aims to accomplish and the problems it intends to solve. A clear program purpose guides the design and implementation of the program, ensuring that it meets the intended requirements and user needs.
#### Identifying Program Purpose
To identify the purpose of a program, ask yourself:
1. What task or problem does the program aim to address?
2. What results or outputs should the program produce?
3. Who will use the program and how will it benefit them?
By answering these questions, you can define the program's purpose and focus on developing functionalities that align with its intended use.
##### Example: Simple Calculator Program
**Program Purpose**: The purpose of a simple calculator program is to perform basic arithmetic calculations between two numbers. It should provide the user with the ability to calculate the sum, product, quotient, and difference of the given numbers.
### Algorithms: The Step-by-Step Process
In computer programming, an algorithm is a set of instructions or a step-by-step process to solve a specific problem or perform a task. It serves as the foundation of a program, guiding the computer on how to execute tasks in a logical and organized manner. Let's explore the concept of a program's algorithm and its step-by-step process:
#### Defining an Algorithm
An algorithm is like a recipe for a computer. It provides a clear set of instructions that outline the exact steps to be followed to accomplish a particular goal. These instructions are written in a way that a computer can understand and execute them.
#### Step-by-Step Process
A program's algorithm breaks down a complex task into smaller, manageable steps. Each step represents a specific action that needs to be performed by the computer. These steps are executed in a sequential order, one after another, until the desired outcome is achieved. The step-by-step process ensures that the program flows logically and consistently.
#### Importance of a Clear Algorithm
Having a clear and well-defined algorithm is crucial for developing effective programs. It helps programmers organize their thoughts and plan the program's logic before writing the actual code. A clear algorithm allows for easier debugging, maintenance, and collaboration between programmers.
##### Example 1: Algorithm for Simple Calculator Program
**Program Algorithm**:
1. Start
2. Input the first number
3. Input the second number
4. Add the first and second numbers to calculate the sum
5. Multiply the first and second numbers to calculate the product
6. Divide the first number by the second number to calculate the quotient
7. Subtract the second number from the first number to calculate the difference
8. Output the sum, product, quotient, and difference
9. End
##### Example 2: Algorithm for Calculating the Area of a Rectangle
Let's consider an algorithm for calculating the area of a rectangle using the `length` and `width` values:
1. Start
2. Input the value of `length`
3. Input the value of `width`
4. Multiply `length` by `width` and assign the result to `area`
5. Output the value of `area`
6. End
In this example, the algorithm begins by taking inputs for `length` and `width`. It then multiplies these values to calculate the `area` and outputs the result. Finally, the algorithm ends.
#### Iteration and Decision-Making
Algorithms can also include iteration (repeating steps) and decision-making (choosing different paths based on conditions). These concepts allow programs to handle different scenarios and make dynamic choices.
#### Refining and Improving Algorithms
Programmers continuously refine and improve algorithms to make programs more efficient, reliable, and user-friendly. They analyze the steps, identify potential issues or optimizations, and modify the algorithm accordingly.
#### Summary
A program's algorithm represents the step-by-step process or set of instructions that guide a computer in solving a problem or performing a task. Understanding and designing clear algorithms are essential skills for effective programming. With a well-defined algorithm, programmers can develop structured and efficient programs.