Mon. Jan 23rd, 2023

Loops

Loops (iterative structures) are used in order to repeat blocks of code. Iterative structures are separated into two groups: definite iteration and indefinite iteration.

Definite Iteration

Definite iteration is used where the number of iterations is known in advance. For example, if you want to repeat something ten times, you would use definite iteration.

FOR

A for loop is used to repeat code a set number of times. A variable is declared to keep count of the number of iterations completed.

C#
for (int x=0; x<10; x++)
{
    //Code to repeat goes here between the curly braces
    //A variable called 'x' has been created and it will
    //count up from 0 to 9, for ten iterations
}

Python
for x in range(10):
    #Code to be repeated goes here - indented
    #A variable called 'x' has been created and it will take
    #values 0 to 9, for a total of ten iterations


Pseudocode
for x = 1 to 10
    Steps to run go here
next / endfor

Indefinite Iteration

There are many occasions when you don’t know in advance how many times a process needs to be repeated. For these, you use indefinite iteration. For example, asking a user to enter a valid password – you don’t know how many attempts this will take ahead of time.

While

A while statement is followed by a condition – as long as the condition evaluates to true then the associated code will be run.

C#
bool ok = false;
while (!ok) {
    //Code to repeat here between curly braces
    if (LoginOK()) { 
        ok = true;
    }
}
//Execution of program continues here once ok is true 
//NB: LoginOK() would be a user defined function, not shown


Python
ok = False
while ok == False:
    #Code repeated goes here, indented
    if LoginOK() == True:
        ok = True
#End of indent means code continues here once ok is true
#NB: LoginOK() refers to a user defined function, not shown


Pseudocode
while condition == true
    Indent items to be repeated
endwhile

Break

A break command will cause an iterative structure to end immediately, and control of the program will pass to the first instruction after the loop ends. It does not matter whether the condition in the loop has been met (e.g. a FOR loop does not need to have completed).

Although break statements are useful, use them with care as they make code more difficult to follow, which could lead to maintenance issues in future.