Resources | Subject Notes | Computer Science
Write pseudo-code for 1D and 2D arrays.
A 1D array is a sequence of elements of the same data type, stored in contiguous memory locations. It's often used to represent lists of items.
array [array_name][array_size];
array_name[0] = value; array_name[1] = value; // ... and so on
element = array_name[index];
array_name[index] = new_value;
for i = 0 to array_size - 1 do // Perform operation on array_name[i] end for
The following pseudo-code calculates the sum of all elements in a 1D array.
Step | Description | Pseudo-code |
---|---|---|
1 | Declare an array of integers. | array[int] [10] |
2 | Initialize the array with some values. | array[0] = 10; array[1] = 20; array[2] = 30; |
3 | Set a variable to store the sum. | sum = 0; |
4 | Iterate through the array. | for i = 0 to 9 do sum = sum + array[i]; end for |
5 | Output the sum. | print sum; |
A 2D array is an array of arrays. It's used to represent tables or matrices, where elements are organized in rows and columns.
array [array_name][data_type][number_of_columns];
array_name[row][column] = value;
element = array_name[row_index][column_index];
array_name[row_index][column_index] = new_value;
for row = 0 to number_of_rows - 1 do for column = 0 to number_of_columns - 1 do // Perform operation on array_name[row][column] end for end for
The following pseudo-code transposes a 2D array, swapping rows and columns.
Step | Description | Pseudo-code |
---|---|---|
1 | Declare a 2D array of integers. | array2d [int] [3][4] |
2 | Initialize the array with some values. | array2d[0][0] = 1; array2d[0][1] = 2; array2d[0][2] = 3; array2d[0][3] = 4; array2d[1][0] = 5; array2d[1][1] = 6; array2d[1][2] = 7; array2d[1][3] = 8; array2d[2][0] = 9; array2d[2][1] = 10; array2d[2][2] = 11; array2d[2][3] = 12; |
3 | Create a new 2D array with swapped dimensions. | transposed_array [int] [4][3]; |
4 | Transpose the elements. | for i = 0 to 2 do for j = 0 to 3 do transposed_array[j][i] = array2d[i][j]; end for end for |
5 | Output the transposed array. | print transposed_array; |