Arrays

An array stores many pieces of data but in the same variable. For example I could save the marks for 5 students in an array like:

array

This array has 5 elements (note that you usually start counting at 0 with arrays!) but they all have just one variable name (studentMarks). To refer to a specific mark you place the index of the mark after the variable name, usually in brackets. For example, you would refer to the mark of 84 as:

// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
// array index
studentMarks[3]
# array (or list) index
studentMarks[3]

Arrays are an important programming concept because they allow a collection of related objects to be stored within a single variable. To declare an array, you usually must specify how many elements will be in the array during the declaration. This is because the compiler needs to reseve the required memory inside the the computer to stare all these variables. (There are ways to store groups of data where the size will change during the running of the program and we will get to them.)Here we are declaring the variable studentMarks and allowing 5 items in it:

// array index
int studentMarks[5];
// array index
int studentMarks[5];
// array index
int[] studentMarks = new int[5];
// array index
var studentMarks[5]int
// array index
int [] studentMarks = new int[5];
// array index
let studentMarks = new Array(5)
# array (or list) index
studentMarks = []

Once you have an array, you will need to loop over it to add items to it or to see what the values are. It is usually a bad idea to Hard Code your loop ending point to a value. An array knows how many elements are in it and you should always use this. If someone changes the size of the array in the declaration, then no othe code will have to be changed.

Here is a code example of creating an array, placing values into it and then reading data out of it:

Code for Creating an Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses an array

#include <stdio.h>

int main() {
    // this function uses an array

    int studentMarks[5];
    int aSingleMark;

    // get length of array
    int arrayLength = sizeof(studentMarks) / sizeof(studentMarks[0]);

    // input
    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        printf("Enter a mark (percentage): ");
        scanf("%d", &aSingleMark);
        studentMarks[loop_counter] = aSingleMark;
    }
    printf("\n");
    printf("Here are the 5 marks:\n");

    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        printf("%d%% ", studentMarks[loop_counter]);
    }

    printf("\n");
    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses an array

#include <iostream>


int main() {
    // this function uses an array

    int studentMarks[5];
    int aSingleMark;

    // get length of array
    int arrayLength = sizeof(studentMarks) / sizeof(studentMarks[0]);

    // input
    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        std::cout << "Enter a mark (percentage): ";
        std::cin >> aSingleMark;
        studentMarks[loop_counter] = aSingleMark;
    }
    std::cout << std::endl;
    std::cout << "Here are the 5 marks:" << std::endl;

    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        std::cout << studentMarks[loop_counter] << "% ";
    }

    std::cout << "" << std::endl;
    std::cout << "\nDone." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program uses an array

using System;

class Program
{
    static void Main() {
        // this function uses an array

        int[] studentMarks = new int[5];
        int aSingleMark;

        // get length of array
        int arrayLength = studentMarks.Length;

        // input
        for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
            Console.Write("Enter a mark (percentage): ");
            aSingleMark = Convert.ToInt32(Console.ReadLine());
            studentMarks[loop_counter] = aSingleMark;
        }

        Console.WriteLine();
        Console.WriteLine("Here are the 5 marks:");

        for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
            Console.Write(studentMarks[loop_counter] + "% ");
        }

        Console.WriteLine();
        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses an array
 */

package main

import (
	"fmt"
)

func main() {
	// this function uses an array

	var studentMarks [5]int
	var aSingleMark int

	arrayLength := len(studentMarks)

	// input
	for loopCounter := 0; loopCounter < arrayLength; loopCounter++ {
		fmt.Print("Enter a mark (percentage): ")
		fmt.Scan(&aSingleMark)
		studentMarks[loopCounter] = aSingleMark
	}

	fmt.Println()
	fmt.Println("Here are the 5 marks:")

	// get length of array
	for loopCounter := 0; loopCounter < arrayLength; loopCounter++ {
		fmt.Printf("%d%% ", studentMarks[loopCounter])
	}

	fmt.Println()
	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * This program uses an array
 * .... this was linted by GitHub Actions
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // this function uses an array

    int[] studentMarks = new int[5];
    int aSingleMark;

    // get length of array
    int arrayLength = studentMarks.length;

    // input
    Scanner scanner = new Scanner(System.in);
    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        System.out.print("Enter a mark (percentage): ");
        aSingleMark = scanner.nextInt();
        studentMarks[loop_counter] = aSingleMark;
    }
    System.out.println();
    System.out.println("Here are the 5 marks:");

    for (int loop_counter = 0; loop_counter < arrayLength; loop_counter++) {
        System.out.print(studentMarks[loop_counter] + "% ");
    }

    System.out.println();
    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program uses an array
 */

const prompt = require('prompt-sync')()
const studentMarks = new Array(5);
let aSingleMark;

// get length of array
const arrayLength = studentMarks.length;

// input
for (let loopCounter = 0; loopCounter < arrayLength; loopCounter++) {
  aSingleMark = parseInt(prompt("Enter a mark (percentage): "));
  studentMarks[loopCounter] = aSingleMark;
}

console.log();
console.log("Here are the 5 marks:");

for (let loopCounter = 0; loopCounter < arrayLength; loopCounter++) {
  process.stdout.write(studentMarks[loopCounter] + "% ");
}

console.log();
console.log("\nDone.");
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses an array
"""


def main():
    """this function uses an array"""

    student_marks = []

    # input
    for loop_counter in range(0, 5):
        a_single_mark = int(input("Enter a mark (percentage): "))
        student_marks.append(a_single_mark)

    print("")
    print("Here are the 5 marks:")

    for loop_counter in range(0, len(student_marks)):
        print(f"{student_marks[loop_counter]}% ", end="")

    print("")
    print("\nDone.")


if __name__ == "__main__":
    main()