Objectives

Students will be able to:

  • understand that data a count-controlled loop can be used to iterate through an entire array.

Data structures

So now we know that we can populate a data structure known as an array with data.

The data will have the same datatype. For example, we could have an array of STRING data, an array of DOUBLE data or an array of BOOLEAN data!

Let's populate an array with some INTEGER data:

Let's populate an array with random integers:

0123456

What we should know:

  • Each item in the data structure has the same datatype
  • The length of the above array is 7.
  • Each element in the array has a unique index. In Python, the indexes start at 0.

We can add all of the data stored in the array together:

total = nums[0] + nums[1] + nums[2] + nums[3] + nums[4] + nums[5] + nums[6] =

A marriage made in heaven

Do you remember count-controlled loops? FOR loops?!

Do you remember this line of program code:

for i in range(7):

What range does the variable i step across as it is controlling the loop?

[0,1,2,3,4,5,6]

 

Wow! These are the same numbers as the indexes of the above array. So, could we do this:

nums = [3,6,4,2,8,9,1]

for i in range(7):

print(nums[i])

Challenge

Here is an array of integers:

nums = [4,6,8,1,5,8,4,1,3,8,7]

With your partner, can you write a program that will count the number of times 4 appears in the array.

Try first, don't peek at the answer too early.

If you get it, let's continue to the exercises.

Tags

iterateauto-indent variablecompile sum machine code count-controlled loop integer pseudocodesyntax