I need help better understanding this piece of code from mosh’s solution on the string exercise, the first one where we were supposed to check if the numbers entered are consecutive.
for (i = 1; i < numbers.Count; i++)
{
if (number [i] != number[i-1] + 1) // This line, i know what it does but dont know how it works
{
is consecutive = false;
break;
}
}
Your help is greatly appreciated
Hi,
Did fix the code a bit. Should anyone still wonder I’ll explain the line.
using System;
public class Program
{
public static void Main()
{
int[] consecutiveNumbers = new int[] {1,2,3,4,5};
int[] notConsecutiveNumbers = new int[] {1,2,3,4,5,7};
DisplayIfNumbersAreConsecutive(consecutiveNumbers);
DisplayIfNumbersAreConsecutive(notConsecutiveNumbers);
}
static void DisplayIfNumbersAreConsecutive(int[] numbers){
bool isConsecutive = true;
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] != numbers[i-1] + 1) // This line, i know what it does but dont know how it works
{
isConsecutive = false;
break;
}
}
Console.WriteLine($"The sequence is {(isConsecutive?string.Empty:"not ")}consecutive");
}
}
Let’s look closer at the line you wonder about:
if (numbers[i] != numbers[i-1] + 1)
At first glance I was wondering how it could work without getting out of bounds. I am so much used to see the second index to actually be i+1
. But this is the opposite that is done here.
We start from index 1 so we are compaaring a given index with the previous one.
So for the very 1st iteration it would translate to if (numbers[1] != numbers[0] + 1)
.
Considering the consecutiveNumbers
array it would be if (2 != 1 + 1)
=> if (2 != 2)
.
This is correct and will remain as long as the sequence is consecutive.
However considering notConsecutiveNumbers
array when i==5
this would be if (numbers[5] != numbers[4] + 1)
=> if (7 != 5 + 1)
=> if (7 != 6)
. Then get into the if
scope and therefore set isConsecutive
to false
and break out of the loop.
Hope this helps.