Use TryParse()
for retrieving integer input from the console. You can do this recursively and in far simpler terms using a ternary operator:
static int GetGCD(int x, int y)
{
// if y is equal to 0, return x.
// if y is not equal to 0, recursive call with x as y and y as the remainder.
return y == 0 ? x : GetGCD(y, x % y);
}
Here we can use the method. Modular arithmetic should be positive. To ensure this, we use the absolute value of the input (Euclidean division).
static void Main()
{
int x, y;
// Get x. Ensure it's an integer.
Console.WriteLine("Input first number: ");
while(!Int32.TryParse(Console.ReadLine(), out x));
// Get y. Ensure it's an integer.
Console.WriteLine("Input second number: ");
while(!Int32.TryParse(Console.ReadLine(), out y));
// Ensure the values being used are positive.
Console.WriteLine(GetGCD(Math.Abs(x), Math.Abs(y)));
Console.ReadKey();
}