An algorithm is a set of steps to solve a problem.
There are often multiple algorithms for the same task.
Algorithms can be created from scratch or adapted from existing ones.
JavaScript
// Example: Find the sum of numbers in an array
let numbers = [1, 2, 3, 4];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
In JavaScript, an algorithm is a clear sequence of steps that solves a specific problem.
Algorithms can be written using loops, conditionals, and functions.
Different programmers might use different approaches for the same task.
This example adds up all the numbers in an array.
Python
# Example: Find the sum of numbers in a list
numbers = [1, 2, 3, 4]
total = 0
for num in numbers:
total += num
print(total)
In Python, an algorithm is just a set of instructions you write to solve a problem.
You can use loops, conditionals, and functions to build algorithms for all kinds of tasks.
There are usually many ways to solve the same problem.
This example adds up all the numbers in a list.
Finding the Maximum Value
Key Points
Use a loop to compare each value.
Keep track of the largest value found so far.
Works in both JavaScript and Python.
JavaScript
let numbers = [5, 3, 9, 1];
let max = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
console.log(max);
This algorithm starts by assuming the first number is the largest.
It loops through the rest of the array, updating the largest number whenever it finds a bigger one.
At the end, it prints the largest value.
Python
numbers = [5, 3, 9, 1]
max_num = numbers[0]
for num in numbers[1:]:
if num > max_num:
max_num = num
print(max_num)
This algorithm starts by assuming the first number is the largest.
It loops through the rest of the list, updating the largest number whenever it finds a bigger one.
At the end, it prints the largest value.
Examples of Existing Algorithms
Key Points
Finding the maximum or minimum value in a list
Calculating sums or averages
Sorting a list
Finding a path through a maze
Compressing data
Why Use Existing Algorithms?
Key Points
Saves development and testing time
Reduces bugs by using proven solutions
Makes debugging easier
Always cite algorithms you use from others
Try It Yourself: Find the Maximum
Key Points
Practice using an algorithm to solve a problem
Use a loop to find the largest number in a list
Try It Yourself (JavaScript)
Write code that prints the largest number in the array. The expected output should be '9'.
Try It Yourself (Python)
Write code that prints the largest number in the list. The expected output should be '9'.