DEV Community

Ted Sá
Ted Sá

Posted on

A is for Algorithms

Algorithm is a set of steps to solve a problem. It can be implemented in activities such as crossing the street and it is divided into steps, for example:

  1. Start the process.

  2. Make sure you are standing up in front of the crosswalk.

  3. Wait till the sign turns red.

  4. Make sure all the cars stopped.

  5. Look both ways.

  6. Start walking.

  7. Get to the other side of the street.

  8. Terminate the process.

That’s an algorithm! It may not be exactly written in a programming language, but it is still an algorithm and it shows some important concepts of it:

-- Start/Terminate: All algorithms have a start and a terminate step. An algorithm can run repeatedly but it needs a start and end. It takes at least one input at the start and it always terminates with at least one output, making it finite.

-- Clear: The instructions are easy to understand and follow, and it is descriptive, basic and simple.

-- Language Independent: The output is the same, even if you translate the instructions to other languages (this applies to programming languages too).

Understanding algorithms help us to understand better our code. What are the steps needed to make our code function? How it can be improved?

Here is an algorithm example of finding out if a number is even or odd:

In English:

  1. Start

  2. Ask for a number

  3. Hear the answer

  4. Divide the number that you just heard by two

  5. If the number has no remainder after the equation, then the number is even

  6. If the number has remainder after the equation, then the number is odd

  7. End

In Java:

import java.util.Scanner;
public class JavaExample
{
    public static void main(String args[])
    {
        int num;
        System.out.print("Enter an Integer number: ");
        Scanner input = new Scanner(System.in);
        num = input.nextInt();
        if ( num % 2 == 0 )
            System.out.println(num+" is an even number.");
        else
            System.out.println(num+" is an odd number.");
    }
} 
Enter fullscreen mode Exit fullscreen mode

Algorithms can also be divided on different types such as recursive, brute force, backtracking, searching, sorting, hashing, divide and conquer, greedy, dynamic programming and randomined.

Personally, I like to think about the algorithm of the code on English and write it down on VSCode as comments, making it a pseudo-code. From there, I start designing my code.

Top comments (0)