*232*

Algorithms are the building blocks of modern computing. Algorithms, the backbone of computer programming, are a set of instructions that define how a problem should be solved. The Algorithms are used to develop software, create applications, and optimize data processing.

In this tutorial, we will explore the fundamentals of algorithms, their various uses, and how they can be applied in various fields.

# Definition of Algorithm

An algorithm is a collection of instructions or steps to resolve a problem. Algorithms are used in all areas of computing, from software engineering to machine learning. They are used to process data, perform calculations, and make decisions. The simplest to the most complicated problems can all be solved using algorithms.

# How Does an Algorithm Work?

An algorithm is a set of instructions or step-by-step procedures used to solve a problem or accomplish a task. It is a logical process that takes an input, performs a set of operations on the input, and produces an output. Algorithms use a combination of mathematical and logical operations to achieve the desired result. Different algorithms may have different steps and operations, but they all follow the same basic principles.

To illustrate how an algorithm works, let’s look at a simple example. Let’s say we want to calculate a triangle’s area. The algorithm for calculating the area of a triangle can be broken down into the following steps:

- Collect the triangle dimensions (base and height)
- Calculate the area using the formula: Area = (base x height) / 2
- Output the area

The algorithm provides a set of instructions that can be followed, step by step, to calculate the area of the triangle. It takes the input, performs the operations, and produces the desired output.

# Why are Algorithms Important to Understand?

Algorithms are important to understand because they provide the basis for solving complex problems efficiently. Algorithms are used to power many of the technologies we use on a daily basis, such as search engines, online banking, and social media platforms. Without algorithms, these technologies would not be possible.

Additionally, understanding algorithms are essential for computer science students, as algorithms are the fundamental building blocks of any computer program. Finally, algorithms can help individuals solve complex problems more quickly and efficiently.

# Example of an Algorithm

## Solving a Backtracking Algorithm for a Maze

```
1. Start at the entrance of the maze.
2. Mark the entrance of the maze as "visited."
3. Move one step forward (up, down, left, right).
4. Check if the current cell has been visited before.
a. If the current cell has been visited before, go back to the previous cell
b. If the current cell has not been visited before, mark it as visited
5. If the current cell is the exit, you are done.
6. If the current cell is not the exit, repeat steps 3-5.
7. If there is no way to move forward, go back and try another route. Repeat steps 3-6 until you find the exit.
```

# Different Types Of Algorithms

Algorithms can be used for various purposes, such as sorting, searching, optimization, pattern recognition, data compression, and more. They are designed to carry out different tasks efficiently and effectively. Below are a few types of Algorithms:

**Search Algorithms:**These algorithms are used to find specific items within a data set. Examples include binary search, linear search, and interpolation search.

**Sorting Algorithms:**These algorithms are used to rearrange data in a certain order. Examples include bubble sort, insertion sort, merge sort, and quick sort.

**Graph Algorithms:**These algorithms are used to traverse and search graphs. Examples include breadth-first search, depth-first search, and shortest path algorithms.

**String Algorithms:**These algorithms are used to manipulate strings of text. Examples include the Rabin-Karp algorithm, Knuth-Morris-Pratt algorithm, Boyer-Moore algorithm, and KMP algorithm.

**Geometric Algorithms:**These algorithms are used to calculate geometric objects. Examples include convex hull algorithms, line-sweep algorithms, and point-location algorithms.

**Numerical Algorithms:**These algorithms are used to solve numerical problems. Examples include numerical integration, numerical optimization, and numerical linear algebra.

**Randomized Algorithms:**These algorithms use randomness as part of their design. Examples include Monte Carlo, randomized search, and sorting algorithms.

**Optimization Algorithms:**These algorithms are used to find the best solution to a problem. Examples include linear programming, dynamic programming, and branch and bound.

**Approximation Algorithms:**These algorithms are used to find approximate solutions to complex problems. Examples include greedy algorithms, local search algorithms, and simulated annealing.

**Machine Learning Algorithms:**These algorithms are used to learn and make predictions from data. Examples include decision tree algorithms, neural network algorithms, and support vector machine algorithms.

Some other important Algorithm types are:

**Data Structures Algorithms:**These algorithms involve manipulating data structures such as arrays, linked lists, and trees. Examples include insertion sort, quicksort, heapsort, binary search, and depth-first search.**Examples**of these types of algorithms are Divide and Conquer algorithms, Dynamic Programming algorithms, Greedy algorithms, Randomized algorithms, Brute Force algorithms, Backtracking algorithms, Linear Programming algorithms, and Graph algorithms. We will discuss all these algorithms in our DSA course in detail in our upcoming tutorials.

- Computational Geometry Algorithms
- Cryptographic Algorithms
- Data Compression Algorithms
- Network Flow Algorithms
- Artificial Intelligence Algorithms
- Image Processing Algorithms
- Robotics Algorithms
- AI Planning Algorithms
- Parallel Algorithms

# Examples of Algorithm

## Algorithm Example 1: Subtract Two Numbers That The User Enters

```
Step 1: Start
Step 2: Declare two numbers, num1 and num2
Step 3: Ask the user to enter num1
Step 4: Store user input in num1
Step 5: Ask the user to enter num2
Step 6: Store user input in num2
Step 7: Calculate the difference between num1 and num2 and assign it to the variable diff
Step 8: Print the result of diff
Step 9: End
```

## Algorithm Example 2: Display Table For Any Number That The User Enters

```
Step 1: Request the user to input any number
Step 2: Store the number in a variable
Step 3: Create a loop to iterate through each number from 1 to 10
Step 4: Within the loop, calculate the result of the number entered by the user multiplied by the current iteration number
Step 5: Print the result of the calculation
Step 6: Increment the iteration number
Step 7: Repeat Steps 3-6 until the loop is finished
```

## Algorithm Example 3: Find The Factorial For Any Number That The User Enters

```
Step 1: Ask the user to enter a number
Step 2: Set the variable ‘result’ equal to 1
Step 3: Create a while loop that will continue until the number the user entered is reached
Step 4: Inside the while loop, set the value of ‘result’ equal to ‘result’ multiplied by the current iteration of the loop
Step 5: Increase the loop by one
Step 6: Output the final value of ‘result’ to the user
```

## Algorithm Example 4: Find The Maximum Number Out Of Three Numbers

```
Step 1: Begin
Step 2: Declare three variables of type integer and assign each one a number
Step 3: Set the variable ‘max’ equal to the first variable
Step 4: Compare the variable ‘max’ to the second variable
Step 5: If the second variable is greater than the variable ‘max,’ set the variable ‘max’ equal to the second variable
Step 6: Compare the variable ‘max’ to the third variable
Step 7: If the third variable is greater than the variable ‘max,’ set the variable ‘max’ equal to the third variable
Step 8: Print the variable ‘max’
Step 9: End
```

## Algorithm Example 5: Check If The Number User Entered Is Prime

```
Step 1: Begin
Step 2: Take in a number from the user
Step 3: If the number is equal to 1, return false
Step 4: Create a loop from 2 to the number 1
Step 5: For each iteration in the loop, check if the number is divisible by the current iteration of the loop.
Step 6: If the number is divisible by the current iteration of the loop, return false
Step 7: If the loop finishes without returning false, return true
Step 8: Display output.
Step 9: End
```

## Algorithm Example 6: Find All Roots Of The Quadratic Equation

```
Input: The coefficients of a quadratic equation ax^2 + bx + c = 0
Output: The roots of the equation
Step 1: Begin
Step 2: Calculate the discriminant D as D = b2 - 4ac
Step 3: If D > 0, there are two real roots. Calculate them as follows:
x1 = (-b + √D)/2a
x2 = (-b - √D)/2a
Step 4: If D = 0, there is only one real root, which is -b/2a
Step 5: If D < 0, there are no real roots.
Step 6: End
```

## Algorithm Example 7: Find The Fibonacci Series

```
Input: A positive integer n
Step 1: Set the first two numbers of the Fibonacci series as 0 and 1.
Step 2: Initialize a loop from 0 to n-1.
Step 3: In the loop, add the previous two numbers of the series and store them in a temporary variable.
Step 4: Print the temporary variable.
Step 5: Replace the first number with the second number and the second number with the temporary variable.
Step 6: Repeat steps 3-5 until n-1
Step 7: End
```

The above algorithm examples are written in Natural Language (also known as Natural Language Specification). Other approaches could also be used to write an algorithm, such as Flowcharts or Pseudocode.

Let’s rewrite the **Algorithm Example 4** in Pseudocode instead of writing it using Natural Language.

## Writing an Algorithm In Pseudocode to Find The Maximum Number Out of Three Numbers

```
MAX ← A
IF A > B
THEN MAX ← B
IF MAX > C
THEN MAX ← C
PRINT MAX
```

# Convert an Algorithm To Code (Program)

Remember one thing, the algorithm you have written will only work if you convert it to code, i.e., any programming language (C, C++, Python). The Algorithm can then be used on computers.

For example, let’s now convert **Algorithm Example 2: Display Table For Any Number That The User Enters** to an executable code.

#include <iostream> using namespace std; int main() { int number; cout << "Please enter a number: "; cin >> number; for (int i = 1; i <= 10; i++) { int result = number * i; cout << number << " x " << i << " = " << result << endl; } return 0; }

## OUTPUT:

```
Please enter a number: 13
13 x 1 = 13
13 x 2 = 26
13 x 3 = 39
13 x 4 = 52
13 x 5 = 65
13 x 6 = 78
13 x 7 = 91
13 x 8 = 104
13 x 9 = 117
13 x 10 = 130
```

#include <stdio.h> int main(void) { int number; printf("Please enter a number: "); scanf("%d", &number); for (int i = 1; i <= 10; i++) { int result = number * i; printf("%d x %d = %d\n", number, i, result); } return 0; }

import java.util.Scanner; public class MultiplicationTable { public static void main(String[] args) { int number; Scanner scanner = new Scanner(System.in); System.out.print("Please enter a number: "); number = scanner.nextInt(); for (int i = 1; i <= 10; i++) { int result = number * i; System.out.println(number + " x " + i + " = " + result); } } }

number = int(input("Please enter a number: ")) for i in range(1, 11): result = number * i print("{} x {} = {}".format(number, i, result))

let number; console.log("Please enter a number: "); number = prompt(); for (let i = 1; i <= 10; i++) { let result = number * i; console.log(number + " x " + i + " = " + result); }

using System; namespace MultiplicationTable { class Program { static void Main(string[] args) { Console.Write("Please enter a number: "); int number = int.Parse(Console.ReadLine()); for (int i = 1; i <= 10; i++) { int result = number * i; Console.WriteLine(number + " x " + i + " = " + result); } } } }

# If Algorithms Have To Be Converted To Code, Why Not Directly Write Code?

Algorithms are high-level conceptual representations of the steps necessary to solve a problem. They are written in plain language, which allows them to be easily understood by humans. On the other hand, writing code requires the programmer to use a specific programming language, which may be difficult for some to understand.

Additionally, algorithms are more abstract than code, which allows the programmer to think about the problem in a more general way, which can lead to more creative solutions. Finally, algorithms can be used to create code, which can be reused in different contexts, thus saving time and effort.