Loops in Pseudocode

Loops are fundamental structures in programming that allow you to repeat a set of instructions multiple times. In pseudocode, we primarily use two types of loops: FOR loops and WHILE loops.

FOR Loops

A FOR loop is used when you know in advance how many times you want to execute a block of code. It's often used to iterate over a range of values or through elements in a collection.

Syntax

LOOP FOR variable FROM start_value TO end_value
    statement(s)
END LOOP

Example

LOOP FOR i FROM 1 TO 5
    OUTPUT i
END LOOP

This loop will output the numbers 1 through 5. For more information on output operations, check the Input/Output in Pseudocode guide.

WHILE Loops

A WHILE loop repeats a block of code as long as a specified condition is true. It's useful when you don't know in advance how many times the loop should run.

Syntax

LOOP WHILE condition
    statement(s)
END LOOP

Example

count = 0
LOOP WHILE count < 5
    OUTPUT count
    count = count + 1
END LOOP

This loop will output the numbers 0 through 4. For more information on variables, refer to the Variables in Pseudocode guide.

Nested Loops

Loops can be nested inside other loops. This is useful for working with multi-dimensional data or when you need to perform complex iterations.

LOOP FOR i FROM 1 TO 3
    LOOP FOR j FROM 1 TO 3
        OUTPUT i, j
    END LOOP
END LOOP

This nested loop will output all combinations of i and j from 1 to 3.

Loop Control Statements

Sometimes you need to alter the flow of a loop. Common control statements include:

LOOP FOR i FROM 1 TO 10
    IF i = 5 THEN
        BREAK
    END IF
    OUTPUT i
END LOOP

This loop will output numbers 1 through 4 and then stop. For more information on if statements, check the If Statements in Pseudocode guide.

Common Loop Patterns

Input Validation

LOOP WHILE TRUE
    INPUT age
    IF age >= 0 AND age <= 120 THEN
        BREAK
    END IF
    OUTPUT "Please enter a valid age between 0 and 120"
END LOOP
OUTPUT "Valid age entered:", age

Processing Collections

total = 0
LOOP FOR i FROM 1 TO 5
    INPUT number
    total = total + number
END LOOP
OUTPUT "The sum is", total

Choosing Between FOR and WHILE Loops

Best Practices

Related Topics

Remember, the goal of pseudocode is to communicate logic clearly. While the exact syntax may vary, the important thing is to convey the looping structure in your algorithm.



Share: https://pseudocode.deepjain.com/?guide=loops