Ali Mukhtar Ali Mukhtar - 1 month ago 6
C# Question

Work out if the numbers are consecutive. For example,"5-6-7-8-9", display: "Consecutive"; otherwise, display "Not Consecutive"

I am doing a basic string exercise question and my logic is something like this but as it an obvious thing that we can not increment a string value like this

temp++
in my case what should be the solution of this :

Console.WriteLine("Input a few numbers separated by a hyphen : ");

var input = Console.ReadLine();

var split = input.Split('-');

var temp = split[0];

for (int i = 1; i < split.Length; i++)
{
temp++;

Console.WriteLine(temp);

if (temp == split[i])
{
Console.WriteLine("Consecutive");
}
}

Answer

You could do:

static bool AreConsecutive(IReadOnlyList<int> numbers)
{
  for (var i = 1; i < numbers.Count; ++i)
  {
    if (numbers[i] != numbers[i - 1] + 1)
      return false;
  }
  return true;
}

Then you could go:

Console.WriteLine("Input a few numbers separated by a hyphen : ");

var input = Console.ReadLine();

var inputParsed = input.Split('-').Select(int.Parse).ToList();

if (AreConsecutive(inputParsed))
  Console.WriteLine("Consecutive");

This will not give a pleasant message in case of bad input (characters that will not parse as integers).

Comments