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.
Exercise 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.
Show example solution
Write int[] grades = { 70, 85, 90 }; for (int i = 0; i < grades.Length; i++) { Console.WriteLine(grades[i]); }
Example solution:
using System;
class Program
{
static void Main()
{
int[] grades = { 70, 85, 90 };
for (int i = 0; i < grades.Length; i++)
{
Console.WriteLine(grades[i]);
}
}
}
Exercise 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.
Show example solution
Write int[,] table = { { 1, 2, 3 }, { 4, 5, 6 } }; and print it with Console.WriteLine(table[0, 1]);
Example solution:
using System;
class Program
{
static void Main()
{
int[,] table = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(table[0, 1]);
}
}
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.
Test yourself
-
With int[] nums = {10, 20, 30}; which safely accesses the last element?
int[] nums = {10, 20, 30}; Console.WriteLine(nums[?]);- nums[3]
- nums[nums.Length - 1]
- nums[2]
- nums[nums.Length]
Show answer
nums[nums.Length - 1] — Correct. nums.Length - 1 always gives the last index; it works even if the size changes.
-
Complete the last-element access
int[] nums = {1, 2, 3, 4}; int last = nums[nums.____ - 1];Show answer
int[] nums = {1, 2, 3, 4}; int last = nums[nums.Length - 1];