Tuesday, 27 October 2015

BASIC CONTROL STRUCTURE

  • Control structures are the basic entities of a structured programming language
  • The mechanism that allow us to control the flow of execution are called control structures. 
  • There are 4 main categories of control structures :
    • Sequence
    • Selection
    • Iteration
    • Branching

SEQUENCE



  • Do one instruction the the next and the next
  • It just executes them in the given sequence or in order listed
  • Most lines of the code in the program belongs to this category.

e.g :
statement 1 is executed first, followed by statement 2, then finally statement 3.


SELECTION


        
  • Selection structures are used to perform ‘decision making‘ and then branch the program flow based on the outcome of decision making
  • Implemented in C/C++ with If, If Else and Switch statements
  • If and If Else statements are 2 way branching statements 
  • Switch is a multi branching statement.
e.g : If - then - else
if (condition) then
   Statement 1;
else
   Statement 2;
  • Condition is a boolean expression 
  • Evaluates either True / False
  • If True - Statement 1 will be executed
  • Otherwise - Statement 2 will be executed
  • S1 & S2 may be single statement or group of statements


ITERATION


  • Iterative construct means that some statements will be executed multiple times until some condition is met
  • Such construct implements a loop structure in which action is executed multiple times, as long as some condition is true 
  • In C, iterative constructs can be implemented using while, do-while, or for loop statements
  • While is an entry controlled loop. Statement inside braces are allowed to execute only if condition inside while is TRUE.
  • Do while is an exit controlled loop.
  • For statement is an entry controlled loop. 
  • The difference between while and for is in the number of repetitions.
  • The for loop is used when an action is to be executed for a predefined number of times. 
  • The while loop is used when the number of repetitions is not predefined.

e.g :


BRANCHING


  • A control structure that allows the flow execution to jump to a different part of the program.
  • This category is rarely used in modular structured programming.

e.g : Go - To Statement


  • It provides an unconditional jump from the 'goto' to a labelled statement in the same function.
  • Use of go-to statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. 
  • Any program that uses a go-to can be rewritten to avoid them.


No comments:

Post a Comment