Arrays (3)
Resources |
Revision Questions |
Computer Science
Login to see all questions
Click on a question to view the answer
1.
A programmer is writing a program to calculate the total cost of items in a shopping basket. The price of each item is stored in an array. The program needs to use a loop to iterate through the array and calculate the total cost. The array is defined as follows:
prices = [2.50, 1.75, 3.00, 1.25, 4.50]
Write pseudocode to show how a loop can be used to calculate the total cost of all items in the shopping basket.
Pseudocode:
- START
- SET
total_cost = 0
- FOR
i = 1 TO length of prices
DO:- ADD
prices[i]
TO total_cost
- END FOR
- DISPLAY
total_cost
- END
2.
Consider an array of student marks in a class. The marks are stored in an array called marks
. Write a program (in a language of your choice) that uses a for loop to find the highest mark in the array and display it. Assume the array has at least one element.
Example Python Code:
def findhighestmark(marks):
highest_mark = marks[0] # Assume the first mark is the highest initially
for mark in marks:
if mark > highest_mark:
highest_mark = mark
print("The highest mark is:", highest_mark)
# Example usage:
student_marks = [75, 82, 90, 68, 88]
findhighestmark(student_marks)
3.
Describe what an array is and explain why arrays are useful for storing multiple values of the same data type in a computer program. Give an example of a scenario where using an array would be more efficient than using multiple individual variables.
An array is a data structure that stores a collection of elements of the same data type in contiguous memory locations. It's essentially a named sequence of variables. Arrays are useful because they allow us to store and access multiple values of the same type using a single variable name and an index. This makes it much more efficient than using separate variables for each value.
For example, consider a program that needs to store the scores of 10 students in a test. If we used 10 individual variables (e.g., score1
, score2
, ... score10
), the code would be verbose and difficult to manage. Using an array (e.g., scores[10]
) would be much cleaner and more efficient. We can easily access each student's score using the array index (e.g., scores[0]
for the first student's score).