Algorithm for Decision Structures & Looping Structures
Decision Structures : Two - Way SelectionIf - Else :
if condition
True alternative
else
False alternative
end if
Example :
if A > B then
Write ( A )
else
Write ( B )
end if
Nested - If :
if condition
True alternative
else
False alternative
end if
else
False alternative
end if
Example : Finding the maximum of three numbers using Nested - If
Read (A, B, C)
If A > B then
if A > C then
max <- A
else
max <- C
end if else if B > C then
max <- B
else
max <- C
end if
end if
Write("Largest value is ", max)
Halt
Decision Structure : Multi - Way Selection
Switch - Case :
select (expression) from
{
case val1 :
statements;
break;
case val2 :
statements;
break;
--------
--------
default;
}
Looping Structure : repeat....while
repeat through step Sn while condition.
-The steps specified in the repeat through statement is the range of loop.
-Sn - steps from repeat statement up to and including step Sn.
Example : Read numbers fro keyboard & print total.
- Start
- Sum <- 0
- Read (num)
- repeat thru step 6 while num > 0
- Sum <- Sum + num
- Read (num)
- Write (Sum)
- Stop
Looping Structure : for
- used if number of repetitions are known before.
- repeat range of loop for values of loop_control_variable.
Example :
- Repeat through step n for i <- 1 to 10
- Repeat for val <- 1 to N
------------
------------
End repeat - Repeat thru step 10 for index -9 to -3 by 3
- Repeat for count <- 2 to 18 by 2
Example : Factorial of a Given Number
- Start
- Read ( N )
- Fact <- 1
- Repeat for i <- N to 1 by -1
fact <- fact * 1
End repeat - Write ("factorial of N is ", fact)
- Stop
Looping Structure : Do - While
Used when the loop need to be executed at least once.
the loop repeat until the condition is satisfied.
Repeat for i <- 1 to N
------
------
if condition then
end repeat until condition
Exit loop
End if
------
------
End repeat
0 Comments