02 May 2012

The Selection Structure

Selection is used to allow a program to choose between two processes, depending on a condition.
The commonest form of selection uses the 'IF' keyword.

The 'IF' structure comes in two basic forms:

1.
IF (condition) Then
          Statement(s)
END IF

2.
IF (condition) Then
           Statement(s)
ELSE
           Statement(s)
END IF

(condition) is an expression which can be evaluated True or False; for example Age is greater than 17 or Yearly Salary is less than or equal to $30,000.

The selection structure may then be used as follows:

IF Age > 17
    Register to Vote
END IF

IF Yearly Salary <= 30
    Tax = 5,000
ELSE
    Tax = 5,000 + (Yearly Salary * 0.1)
END IF

Note the indetation which clearly shows the beginning and end of the selection structure.

'C' Syntax for 'if' keyword

if(Age > 17)
{ 
    printf("You can vote");
}
if(yearlySalary <= 30000)
{ 
    Tax = 5000;
}
else
{ 
    Tax = 5000 + YearlySalary * 0.1;
}

Note the use of {} to show the extent of the selection structure.
Note also the use of indentation which improves readability of code.

The relation operator which may be used in 'C' are:


Relational Operator Meaning Example
< less than Age < 21
> greater than Salary > 30000
<= less than or equal to Height <= 198
>= greater than or equal to Weight >= 80
== equal to Mark == 100
!= not equal to Number != 0

Note the use if the double '=' sign to signify 'is equal to' (Remember that a single '=' sign represent an assignment)


Nested Selection

You can put 'if' statements inside other 'if' statements. This is called "Nesting".

Get Age
If Age < 10
    Display "You are a baby"
Else
    If Age < 30
        Display "You are young"
    Else
        Display "You are past it"
    End If
End If

No comments:

Post a Comment