Friday, April 4, 2014

Basic programming theory: The 3 main constructs of a computer program

At a low level, structured programs are composed of simple program flow constructs. These are Sequence, Selection and Iteration (SSI). I often refer them in short with SSI in my regular communication with my peers.

Sequence: One Step at a Time. Executing the program code (or algorithm) line by line, one at a time. e.g. Line 1, line 2 and line 3 and so on... An ordered execution of program statements one by one successively without skipping any step.

Selection: It is like Branching - given a criteria, change the path through the program. The execution sequence is controlled using ‘if’ or ‘if else’ or 'switch'. The 'if'' or 'switch' statement is a testing a condition evaluating a variable etc. to control and change the execution of the program depending the environment. A sequence of program/algorithm lines can be formed as a 'selection block' and can be executed or skipped depending on the condition composed with if/switch.

Iteration (and Recursion) a.k.a Repetition or Looping: Do something multiple times until/while a criteria (program reached to a certain state) is met or a fixed number of times using for statement. Iteration is typically used to refer to collections and arrays of variables and data. Iteration means to visit every item in the collection/array, usually in order but it may be in an irregular order, however each item is visited only once. Counting from 1 to 10, you are iterating over the first 10 numbers.

A sequence of program/algorithm lines can be formed as a block known as 'iteration block' and can be executed for a given number of times, based on certain conditions. Some times it is necessary to perform same step for a number of times. If same statement is written repetitively, it will increase program size. To avoid this problem, iteration is used. The statement written in iteration block is executed for a given number of times, based on certain condition.

Note: Recursion is the process a procedure goes through when one of the steps of the procedure involves invoking the procedure itself.

No comments:

Post a Comment