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:
Start the process.
Make sure you are standing up in front of the crosswalk.
Wait till the sign turns red.
Make sure all the cars stopped.
Look both ways.
Start walking.
Get to the other side of the street.
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:
Start
Ask for a number
Hear the answer
Divide the number that you just heard by two
If the number has no remainder after the equation, then the number is even
If the number has remainder after the equation, then the number is odd
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.");
}
}
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)