Resources | Subject Notes | Computer Science
Arrays are fundamental data structures in computer science used to store a collection of elements of the same data type. These elements are stored in contiguous memory locations and can be accessed using an index.
In many programming languages, arrays are declared with a specific data type and size. Here's a general representation:
data_type [array_name] = {element1, element2, ..., elementN};
For example, an array of 5 integers could be declared as int numbers[5]
.
Elements in an array are accessed using their index within square brackets. The index starts from 0 for the first element.
For example, numbers[0]
refers to the first element, numbers[1]
refers to the second, and so on.
Here are some examples of pseudo-code for common array processing tasks:
Step | Action |
---|---|
1 | Define array numbers of size 5 as integers. |
2 | Assign value 10 to numbers[0]. |
3 | Retrieve value at index 1 using numbers[1]. |
Loops are commonly used to process each element in an array.
FOR i = 0 TO array_size - 1 DO Process array[i] END FOR
Step | Action |
---|---|
1 | Initialize a loop counter i to 0. |
2 | Repeat the following steps until i is equal to array_size - 1. |
3 | Access the element at index i of the array. |
4 | Perform the desired operation on the accessed element. |
5 | Increment i by 1. |
The following pseudo-code demonstrates how to find the maximum value in an array.
maximum = array[0] FOR i = 1 TO array_size - 1 DO IF array[i] > maximum THEN maximum = array[i] END IF END FOR RETURN maximum
Step | Action |
---|---|
1 | Assume the first element of the array is the maximum. |
2 | Iterate through the remaining elements of the array. |
3 | For each element, compare it with the current maximum. |
4 | If the current element is greater than the maximum, update the maximum. |
5 | After iterating through all elements, the variable 'maximum' will hold the largest value in the array. |
Pseudo-code to calculate the sum of all elements in an array:
sum = 0 FOR i = 0 TO array_size - 1 DO sum = sum + array[i] END FOR RETURN sum
Step | Action |
---|---|
1 | Initialize a variable sum to 0. |
2 | Iterate through each element of the array. |
3 | Add the current element to the sum. |
4 | After iterating through all elements, the variable sum will contain the total sum of all elements in the array. |