Last active
April 5, 2022 19:44
-
-
Save GretaP/af9636813b4be1739c61e3e58365ee5c to your computer and use it in GitHub Desktop.
Solution to an Udemy exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ConsecutiveNumberGist | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//1 - Write a program and ask the user to enter a few numbers separated by a hyphen. | |
//Work out if the numbers are consecutive. | |
//example, if the input is "5-6-7-8-9" or "20-19-18-17-16", display a message: "Consecutive"; otherwise, display "Not Consecutive". | |
Console.WriteLine("Input numbers in the format x-x-x-x, and the program will tell you if they are consecutive (increasing/decreasing by 1 at a time) or not"); | |
var input = Console.ReadLine(); | |
//const string input = "5-6-5-8-9"; | |
Console.WriteLine($"Your input is a set of {(ConsecutiveCheck(input) ? "consecutive" : "non-consecutive")} numbers"); | |
} | |
public static bool ConsecutiveCheck(string input) | |
{ | |
//returns true if string input in format #-#-#-# is consecutive | |
var num = Array.ConvertAll(input.Split("-"), int.Parse); | |
var increment = (num[0] < num[1]) ? 1 : -1; | |
for (var i = 0; i < num.Length-1; i++) | |
{ | |
if (num[i] + increment != num[i + 1]) return false; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment