Syntax+Example (if+Case+All Loops)
Syntax+Example (if+Case+All Loops)
Example: The following program is an example of sequence that calculates the average of two numbers.
declare total as integer
declare average as real
declare a, b as integer
input a
input b
total = a + b
average = total/2
output total, average
i) IF <condition> THEN
<Statement>
END IF
Example 1: (a/i)
Example 2: (a/ii)
total = 15
k=5
input k
IF k >= 3 THEN
k=k*k
total = total + k
ELSE
total = total + k
END IF
print total
b) Syntax of CASE statements: The common format of CASE statement is given below:
CASE Else
< One or more statements >
END SELECT
Example 1:
3. LOOPS: Many problems involve a process that needs to be repeated a specific number of
times. So it is useful to have a technique that performs these loops. There are
number of techniques available such as:
FOR … NEXT
WHILE … DO
REPEAT … UNTIL
a) FOR … NEXT Loop: This is used when the loop is to be repeated a known fixed number of
times. The counter is automatically increased each time the loop is performed. For example, if we
want to perform a loop to add together the ten numbers, we can do that by using For Loop.
Example:
total = 0
For count = 1 to 5 [1, 2, 3, 4, 5]
input number [80, 70, 90, 75, 60]
total= total + number [0+80=80, 80+70=150, 150+90=240, 240+75=315, 315+60=375]
Next count
average = total/5 [75]
Output total, average [375, 75]
b) WHILE … DO Loop: The WHILE … DO loop may be used in preference to the FOR …
NEXT loop; it can also be used when we do not know how many times the loop is to be
performed. The loop is ended when certain condition is true. This condition is checked before
starting the loop.
count = 1
total = 0
While <Condition> Do
input mark/number/data/value/temp/etc
…………………
…………………
count = count + 1
Endwhile
Example:
count = 1
total = 0
While count < = 5 Do
input number
total = total + number
count = count + 1
Endwhile
average = total/5
Output total, average
While Loop:
Pre-conditional loop
Count=1
Count=count+1
Use < or <= sign in condition
Don’t use > or >= sign