8.2.1 Data Structures (1D Arrays) Flashcards
What is an array?
- Collection of variables of the same data type
- Referred to by a single name (identifier)
- Each element is accessed by an index (position)
Often called a data structure
What are the advantages of arrays?
+ can store multiple values under a single identifier
+ reduces the number of variables
+ can use iteration to loop through an array
+ allows for more efficient programming
Basic Array in Pseudocode
INTEGER nums[4]
nums[0] ← 10
nums[1] ← 20
nums[2] ← 30
nums[3] ← 40
Reading and Writing to Arrays
For loops are perfect for iterating through arrays using the counter variable as the index.
Show an Example in Pseudocode
STRING names[10]
OUTPUT “Enter 10 names: “
//store input in each element of the array
FOR i ← 0 TO 9 STEP 1
INPUT names[i]
NEXT i
or
//loop though each element of array and output
FOR i ← 0 TO 9 STEP 1
OUTPUT names[i]
NEXT i
Searching Arrays
Exam questions often ask you to search arrays to find the largest value or to perform some calculation. The example below calculates the average of an array of 100 numbers and finds the highest value
Show an Example in Pseudocode
//store input in each element of the array
FOR i ← 0 TO 100 STEP 1
total ← total + nums[i]
IF nums[i] > highest THEN highest ← nums[i] ENDIF NEXT i
//calculate average
average ← total / 100