Topic 7
Topic 7
Topic 7
A realistic program may require that a logical test be carried out at some particular point within
the program.
There are two broad categories of control statements:
Decisions/branching/selection
Loops/repetitions
Recall relational operators and logical expressions
To form logical expressions, relational operators (<, <=, >, >=) and the two equality
operators (== and !=) are required.
Example of logical expressions
count <= 100
sqrt (a+b+c) 0.0005
answer == 0
balance >= cutoff
ch1 < ‘T’
letter != ‘x’
The logical connectives /logical operators (&& (AND) and || (OR)) and the unary
negation operator ! are also used in the construction of relational expressions
Example
(count <= 100) && (ch1 != ‘*’)
(balance < 1000.0) || ( status ==’M’)
!((pay >= 20000.0) && (status ==’S’))
The conditional ?: also makes use of an expression that is either true or
false eg status = (balance == 0)? (discount =1000.0) : (rate =0.6)
7.1 Decisions
When one of several possible actions is carried out depending on the outcome of the logical test
(Branching) or when one group of statements is selected from several available groups
(selection).
Major decision statement and general syntax :
if statement
if(expression) statement or
if(expression)
{
statement 1;
.
.
.
Statement n;
}
if …else statement
if (expression)
{
statements;
}
else
{
statements;
}
switch statement
causes a particular group of statements to be chosen from several available
choices (groups)
the selection is based upon the current value of an expression which is
included within the switch statement.
switch (expression)
{
statements;
}
switch(expression)
{
case expression 1: { statements;}
break;
case expression 2:{statements;}
break;
.
.
.
break;
case expression n:{ statements;}
break;
default:{statements;}
break statement
break statement is used to terminate loops or exit from a switch.