3.9 Algorithms - Syntax Terrors

What is an Algorithm?

Key Points

  • 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.