c# · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item in an array has an , starting at 0.
Each item has an index: its position number. C# starts counting at 0, so the first item is planets[0] and the second is planets[1]. Square brackets after the name pick one out.
So the last item is always at Length - 1. To change an item, put a new value in its slot: planets[1] = "Mars";. An array's size is fixed, so you cannot add slots.
Ask for a slot that is not there and C# stops with an , an error that happens while the program runs. This one is called IndexOutOfRangeException.
using System;
string[] planets = { "Mercury", "Venus", "Earth" };
Console.WriteLine(planets[0]);
Console.WriteLine(planets[planets.Length - 1]);
planets[1] = "Mars";
Console.WriteLine(string.Join(", ", planets)); Think of the index as how many steps from the start, so the first item is 0 steps away.
guess first
Which planet is at index 1?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
string[] planets = { "Mercury", "Venus", "Earth" };
Console.WriteLine(planets[1]);
your turn
Your turn. Join the team.
Swap one player for you. Type an index, 0, 1 or 2, in the square brackets, and your name between the quotes. Then press run.
output
press run to see what happens
fix it
We want the last cake, but C# crashes. Fix it!
output
press run to see what happens
- C# stopped with an exception. Count the cakes, then count their indexes.
- Three cakes have indexes 0, 1 and 2. There is no slot 3.
- Change 3 to 2 on line 4, or use
cakes.Length - 1, then press run.
nailed it
you can pick any item you like. :D
- The index of the first item is 0.
- The last item is at
Length - 1. - A missing slot stops the program with an exception.
new words in your collection
- index
- exception
This lesson isn’t saved. A free account remembers every lesson you finish.