Now that we've explored the fundamental building blocks of algorithms – sequences, selections, and iterations – let's see how they come together to solve simple, yet illustrative, problems. Understanding these basic examples is crucial because complex algorithms are often just intricate combinations of these fundamental patterns. We'll start with a very basic task: checking if a number is even or odd.
To determine if a number is even or odd, we need to consider its divisibility by 2. If a number divided by 2 leaves no remainder, it's even. Otherwise, it's odd. This is a classic case where we need to make a decision – a 'selection' in algorithmic terms. We'll use the modulo operator (%) for this, which gives us the remainder of a division.
function checkEvenOrOdd(number) {
if (number % 2 === 0) {
return 'Even';
} else {
return 'Odd';
}
}Let's break down the logic here. The checkEvenOrOdd function takes a number as input. The if statement is our 'selection'. It checks the condition number % 2 === 0. If this condition is true (meaning the remainder is 0), the function returns 'Even'. If the condition is false, the else block is executed, and the function returns 'Odd'. This is a straightforward application of a single conditional statement.
graph TD
A[Start]
B{Input Number}
C{Is Number % 2 === 0?}
D[Output: Even]
E[Output: Odd]
F[End]
A --> B
B --> C
C -- Yes --> D
C -- No --> E
D --> F
E --> F
Next, let's consider a problem that involves repetition: calculating the sum of numbers from 1 up to a given number. This is a common task, and it clearly demonstrates the need for an 'iteration'. We'll use a loop to go through each number and add it to a running total.
function sumUpTo(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum = sum + i;
}
return sum;
}In this sumUpTo function, we initialize a variable sum to 0. The for loop is our 'iteration'. It starts with i at 1, and as long as i is less than or equal to n, it increments i by 1 in each step. Inside the loop, sum = sum + i adds the current value of i to our running total. Once the loop finishes (when i becomes greater than n), the final sum is returned.