Loops and If Statements

As you can probably guess by now, yes you can place loops inside if statements and if statements inside loops.

An if statement inside a loop would (in most computer programming languages), take the generic form of:

FOR counter in range(n)
IF (Boolean expression) THEN
Statements to be performed
ENDIF
END

or using While loops:

WHILE counter1 <= n :
IF (Boolean expression) THEN
Statements to be performed
ENDIF
counter1 = counter1 + 1
END

Here is one of the most well-known examples of the exercises that you might be given as the opening question in a junior data scientist job interview.

The task is: Go through all the whole numbers up until 100 (1 to 100). Print ‘Fizz’ for every number that’s divisible by 3, print ‘Buzz’ for every number divisible by 5, and print ‘Fizz-Buzz’ for every number divisible by 3 and by 5! If the number is not divisible either by 3 or 5, print out the number.

Top-Down Design for Loops and If Statements

Top-Down Design for Nested Loops

Flowchart for Loops and If Statements

for Nested Loops flowchart

Pseudocode for Loops and If Statements

FOR counter1 in range(10)
FOR counter2 in range(10)
SHOW Odometer {counter1}{counter2}
END
END

Code for the Loops and If Statements

Example Output

Code example output