成人快手

Algorithms - EdexcelNesting

Algorithms are step-by-step plans for solving problems. Algorithms can be designed using pseudo-code, flowcharts, written descriptions and program code. There are also some standard algorithms for searching and sorting.

Part of Computer SciencePrinciples of computer science

Nesting

Nesting is when one programming construct is included within another. Nesting enables powerful yet simple programming. It reduces the amount of code needed, while making it simple for a programmer to debug and edit.

Nested selection

When using , the number of possible paths at a decision point can be increased by including one selection within another.

This program uses nested selection:

SEND 鈥楬ow old are you?鈥 TO DISPLAY
                    RECEIVE age FROM (INTEGER) KEYBOARD
                    IF age > 16 THEN
                    聽聽聽聽聽SEND 鈥榊ou are old enough to drive a car
                    聽聽聽聽聽and ride a moped鈥 TO DISPLAY
                    ELSE
                    聽聽聽聽聽IF age = 16 THEN
                    聽聽聽聽聽聽聽聽聽聽SEND 鈥榊ou are old enough to ride
                    聽聽聽聽聽聽聽聽聽聽a moped!鈥 TO DISPLAY
                    聽聽聽聽聽ELSE
                    聽聽聽聽聽聽聽聽聽聽SEND 鈥楥ome back when you are older!鈥
                    聽聽聽聽聽聽聽聽聽聽TO DISPLAY
                    聽聽聽聽聽END IF
                    END IF

Here, there are two conditions that may be tested, resulting in three possible paths to follow. The second condition is only tested if the result of the first test is FALSE.

Nested selection can be built up over and over to include many possibilities and paths for a program to follow. It enables complex decisions to be made.

Nested iteration

can also be nested. This program uses two count-controlled loops - one within another - to print out the times table for all numbers from one to ten:

FOR x FROM 1 TO 10 DO
                    聽聽聽聽聽FOR y FROM 1 TO 10 DO
                    聽聽聽聽聽聽聽聽聽聽SET result TO y * x
                    聽聽聽聽聽聽聽聽聽聽SEND y & " * " & x & " = " & result
                    聽聽聽聽聽聽聽聽聽聽TO DISPLAY
                    聽聽聽聽聽END FOR
                    END FOR

For every iteration of x, y is iterated ten times.

This program uses condition-controlled WHILE loops, one within another, to print out the times table for all numbers from one to ten:

SET x TO 1
                    SET y TO 1
                    WHILE x < 11 DO
                    聽聽聽聽聽WHILE y < 11 DO
                    聽聽聽聽聽聽聽聽聽聽SET result TO y * x
                    聽聽聽聽聽聽聽聽聽聽SEND y & " * " & x & " = " & result
                    聽聽聽聽聽聽聽聽聽聽TO DISPLAY
                    聽聽聽聽聽聽聽聽聽聽y = y + 1
                    聽聽聽聽聽END WHILE
                    聽聽聽聽聽SET y TO 1
                    聽聽聽聽聽SET x TO x + 1
                    END WHILE

For every iteration of x, y is iterated ten times.