CodeBlanks Logo Icon CodeBlanks

Summary - Arrays

Use single-dimensional and matrix arrays to write a grade table.

Summary - Arrays

In this group you learned one-dimensional arrays, index access, .Length, the int[,] matrix and the int[][] jagged array. Now you will combine them to write a grade table.

Across two exercises you will first walk a grades array with for and print each grade, then read a specific cell from a two-row matrix. One-dimensional and multi-dimensional arrays appear side by side here.

Practice Print grades with for

Declare a grades array with the value { 70, 85, 90 }. Use the pattern for (int i = 0; i < grades.Length; i++) to print each element with Console.WriteLine(grades[i]). The output should be 70, 85, 90.

Starter code

Program.cs
using System;

class Program
{
    static void Main()
    {
        // Write the grades loop here
    }
}

Sample solution

Program.cs
using System;

class Program
{
    static void Main()
    {
        int[] grades = { 70, 85, 90 };
        for (int i = 0; i < grades.Length; i++)
        {
            Console.WriteLine(grades[i]);
        }
    }
}

Expected output

70
85
90

Practice Read a cell from the matrix

Declare a table matrix with the value { { 1, 2, 3 }, { 4, 5, 6 } }. Print table[0, 1] with Console.WriteLine. The output should be 2.

Starter code

Program.cs
using System;

class Program
{
    static void Main()
    {
        // Declare the matrix and print a cell
    }
}

Sample solution

Program.cs
using System;

class Program
{
    static void Main()
    {
        int[,] table = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine(table[0, 1]);
    }
}

Expected output

2

The arrays side by side

You now know three array types: the one-dimensional int[], the matrix int[,] and the jagged int[][]. Which one to pick depends on the shape of the data.

For one-dimensional ordered data use int[]; for row-and-column data int[,]; for rows of different sizes int[][]. Use .Length and GetLength to safely check bounds.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 With int[] nums = {10, 20, 30}; which safely accesses the last element?

Program.cs
int[] nums = {10, 20, 30};
Console.WriteLine(nums[?]);
  • nums[3]
  • nums[nums.Length]
  • nums[2]
  • nums[nums.Length - 1] Correct answer

Explanation: nums.Length - 1 always gives the last index; it works even if the size changes.

2 Complete the last-element access

Question
int[] nums = {1, 2, 3, 4};
int last = nums[nums.____ - 1];
Answer
int[] nums = {1, 2, 3, 4};
int last = nums[nums.Length - 1];

Explanation: nums.Length - 1 always gives the last index.

All lessons in Beginner