Using Arrays

  • Arrays are used to store and manage multiple values of the same data type efficiently
  • They can be used for tasks such as storing student scores, calculating averages, and managing inventory data

Using variables in arrays

  • Variables can be used as indexes in arrays to access and modify elements by repeatedly checking every element
  • This is useful when iterating through the array using loops or performing calculations based on user input

What is the first index value?

  • The first index can be either 0 or 1, depending on the programming language and personal preference
  • Most programming languages, such as Python, Java, and Visual Basic, use 0 as the first index

Pseudocode example:

DECLARE scores[5] OF INTEGER

FOR i FROM 0 TO 4

INPUT scores[i]

ENDFOR

Python example:

scores = [0] * 5

for i in range(5):

scores[i] = int(input())

Java example:

int[] scores = new int[5];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
    scores[i] = scanner.nextInt();
}

Visual Basic example:

Dim scores(5) As Integer
For i As Integer = 0 To 4

   console.Writeline("Enter score: ")
    scores(i) = Console.ReadLine())
Next

Using Iteration

  • Loops can be used to write values into arrays, iterating through each element and assigning a value
  • Iteration can also be used to read values from arrays, traversing through each element and performing operations or outputting the value
  • Nested iteration is useful for working with multi-dimensional arrays, such as 2D arrays, where you need to iterate through rows and columns

Pseudocode example:

DECLARE scores[3][3] OF INTEGER
FOR i FROM 0 TO 2
   FOR j FROM 0 TO 2
      INPUT scores[i][j]
   ENDFOR
ENDFOR

FOR i FROM 0 TO 2
   FOR j FROM 0 TO 2
      OUTPUT scores[i][j]
   ENDFOR
ENDFOR

Python example:

scores = [[0] * 3 for _ in range(3)]
for i in range(3):
    for j in range(3):
        scores[i][j] = int(input())

for i in range(3):
    for j in range(3):
        print(scores[i][j])

Java example:

int[][] scores = new int[3][3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        scores[i][j] = scanner.nextInt();
    }
}

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.print(scores[i][j] + " ");
    }
    System.out.println();
}

Visual Basic example:

Dim scores(2, 2) As Integer
For i As Integer = 0 To 2
    For j As Integer = 0 To 2

        Console.Writeline("Enter score: ")
        scores(i, j) = Console.ReadLine())
    Next
Next

For i As Integer = 0 To 2
    For j As Integer = 0 To 2
        Console.Write(scores(i, j) & " ")
    Next
    Console.WriteLine()
Next

Loading

error: Content is protected !!