Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run (lines separated by spaces)?
int[] nums = [4, 8, 15];
for (int i = 1; i <= nums.Length; i++)
{
Console.WriteLine(nums[i]);
}8 15, then an IndexOutOfRangeException
- Expecting
4 8 15: indexes start at0, so a loop fromi = 1skipsnums[0], andi <= nums.Lengthtakes it on to index3, past the end. - Expecting a
0past the end or a compile error: C# checks every index when the program runs, and index3stops it with anIndexOutOfRangeException.
- How would you fix the loop so that it prints every element with no exception?
- What does the program print if the condition becomes
i < nums.Length?