Algorithm

An algorithm is a set of instructions to perform a specific task. It can be a simple process, such as adding two numbers, bake a cookie, or perform a complex operation, such as creating a war game.

An algorithm in Computer Science

An algorithm is a set of step-by-step instructions in order to solve a problem or perform a task. Algorithms are commonly used in Software Engineering for planning and solving problems.

Characteristics  of  an algorithm

Input:  An algorithm needs  data for processing, in a few case data inputs is not required

Output: An algorithm is expected to produce the desired outcome(s)

Definite: The instruction must be clean and with any contradictions (unambiguous).

 Finite: An algorithm must terminate after a finite number of steps.

Control structures in the algorithm

1. Sequence: In this structure, steps are placed one after the other starting from up to down to solve the problems.

2. Branching: In this structure, the decision of based on logical outcome (TRUE or FALSE). It creates two branches, one is executed in case of the TRUE condition, the other is executed in case of the FALSE condition.

3. Repetition(Loop): The Repetition or loop allows a step or set of steps to be executed repeatedly until a condition is matched.

How to write an algorithm

Step 1  Identify  input
An algorithm may need some data (input) to process and produce the outcome. 
Step 2 Define the variables
Variable are placeholder that holds values required to process. Define variables that hold the data for later use.
Step 3 Outline the steps: 
Mention the step (s) using the sequence of steps, branching and loops constructors
Step 4 Output the results:
Display or  return the desired outcome. ​​​​​​​

​​​​​​​​​​​​​​Example 1:  Algorithm add two numbers

 Step 1: Start
 Step 2: Declare variables number1, number2 and sum. 
 Step 3: Read values number1 and number2.
 Step 4: Add number1 and number2 and assign the result to sum
 Step 5: Display sum
 

Example 2:  Algorithm finds if a number is divisible by 7

 Step 1: Start
 Step 2: Declare variables number1
 Step 3: Read value number1 
 Step 4: Check number1 mod 7  is equal to 0 go to step 5 otherwise go    to step 6
 Step 5: Display number1 is divisible by 7
 Step 6: Stop

 

Example 3:  Algorithm  sum of n natural numbers

 Step 1: Start
 Step 2: Declare variables stop, sum =0, start = 1
 Step 3: Ask user to input the stop value
 Step 4: stop = stop value
 Step 5: If start is equal to stop  go to step 8
 Step 6: Add start to sum
 Step 7: Add start to 1
 Step 8: Print sum