Arrays (3)
Resources |
Revision Questions |
Computer Science
Login to see all questions
Click on a question to view the answer
1.
Consider a program that needs to store the names of 5 friends. Write pseudocode to demonstrate how you would use an array to store these names. Include how you would access the name of the second friend in the array.
Here's pseudocode demonstrating the use of an array to store names:
- Declare an array called
friendNames to hold 5 strings. - Assign the names of the friends to the array elements.
friendNames[0] = "Alice"friendNames[1] = "Bob"friendNames[2] = "Charlie"friendNames[3] = "David"friendNames[4] = "Eve"- To access the name of the second friend, use the index 1. The pseudocode would be:
friendName = friendNames[1]. This would assign the value "Bob" to the variable friendName.
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).