Skip to content
Learnearn.uk » Home » Definite Iteration (For Loops)

Definite Iteration (For Loops)

Definite Iteration

Definite Iteration (for loops)

Definite iteration, also known as a definite loop, is used when you know the exact number of iterations or the range over which you want to iterate. It involves iterating a specific number of times or over a predefined range of values. A definite loop is  a loop that is definitely going to end.

Definite iteration is commonly implemented using “for” loops.

Definitely Iteration Edexcel iGCSE Computer Science

 

Index based for loops

Index-based for loops

An index-based for loop iterates over a collection using the indices of the elements. It involves iterating over a range of indices and accessing the elements of the collection using the indices.

Here’s an example of an index-based for loop in Python:

fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
    print(fruits[i])

Output:

apple

banana

cherry

In this example, the for loop iterates over the range of indices (0, 1, 2) of the fruits list. The loop variable i represents the index, and the elements of the list are accessed using the indices (fruits[i]).

Great for:

  • When you need to know the index of the item as well as the item itself
  • When you are iterating through two one-dimensional lists simultaneously and want to get items in both lists at the same index.

 

Object-based For loops

Object-based For loops

An object-based for loop, often referred to as a “foreach” loop, directly iterates over the elements of a collection without using indices. It simplifies the syntax and makes the code more readable by directly accessing the objects.

Here’s an example of an object-based for loop in Python:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Great for:

  • When you don’t need to anything fancy and just need to do something for each item in a list.