Algorithms in Programming
Algorithms are most common thing in programming and we use algorithms in our day today life as well. Lets here talk about algorithms in programming.
An algorithm is a a set of steps used to complete a specific task. They're the building blocks for programming and they allow things like computers, smartphones, and websites to function and make decisions.
There are five important characteristics of an algorithm
- Well-ordered.
- Has unambiguous operations.
- Has effectively computable operations.
- Produces a result.
- Halts in a finite amount of time.
When we are given an algorithm there are several ways to determine the purpose of the algorithm. Sometimes it is clear that the algorithm is simple; however, at other times it is useful to "dry out" the algorithm to see what happens.
Running an algorithm dry means assigning the values to the variables of an algorithm and performing the processing without translating them into code. For that we can use Trace Tables (Desk Checking).
Algorithms can be designed using pseudo-code or flowcharts or both. It focuses on step logic rather than programming language.
Pseudo-Code
Pseudocode is a simple way of describing a set of instructions in a way that is similar to a programming language. In the algorithm, most operations fall into three main categories:
- inputs
- processes
- outputs
Example for pseudo-code for printing stars like this
First lets see the scenario. In first line we need to print one star. then go to next line and print two stars. Then again go to next line and print three stars. Then again go to next line and print four stars and finally go to next line and print five stars.
We can implement above scenario like this
- Start
- Declare counter
- Initialize counter=0
- WHILE counter<5
- counter=counter+1
- FOR counter number of times
- Display "*"
- END FOR
- Print new line
- END WHILE
- Stop
1st line- Start point of the pseudo-code
2nd line- Declare variable for remind counting
3rd line- Initialize that variable
4th line- Start a While loop until counter <5
5th line- counter variable increment by 1
6th line- Start a For loop and run it times of counter variable
7th line- Display star
8th line- End of the For loop
9th line- Go to new line
10th line- If the While loop condition is false End the While loop
11th line- End point
Flowcharts
A flowchart is a diagram that shows an overview of an algorithm. Flowcharts use a variety of standard symbols to represent different elements and arrows to show flow or direction. These symbols are used to build the flowchart and show the step by step solution to the problem.
Common flow diagram symbols
Lets draw a flowchart for above example