'Writing a Program that Divides 2 user outputs without crashing [closed]

I recently started taking a intro to programming course that programs in C# and I am stuck on an assignment that asks us to "Write a program which takes two user input values and divides them without crashing on a divide by zero error. Create a prompt asking the user to input two integer values. Assign each input to its own variable. Create a custom method which takes the second number input and divides it by the first number input. Call the custom method from your Main() method. Your program should not crash if a divide by zero error occurs"

I am still working through the last bit of notes we have for the topic, but I feel like I don't even have a solid foundation to start on! If someone could provide an example for me, that would be great! (I am more of a visual learner rather than take notes and execute)

Thank you in advance!



Solution 1:[1]

As like most programming questions, this question has more than one answer. Also, you did not specified what needs to happen when 0 is given as input2

Here is my answer. (It continously asks a new input for input2)

public static int Divide()
    {
        Console.WriteLine("Enter first number");
        var val = Console.ReadLine();
        int input1 = Convert.ToInt32(val);

        Console.WriteLine("Enter second number");
        val = Console.ReadLine();
        int input2 = Convert.ToInt32(val);

        while (input2 == 0)
        {
            Console.WriteLine("Second number can't be 0");
            val = Console.ReadLine();
            input2 = Convert.ToInt32(val);
        }
        return input1 / input2;
    }

You can call custom function "Divide" by using:

Console.WriteLine("Result is : " + Divide());

in your Main function

And lastly, I advise you to take a look to "Exceptions" and "Try-Catch" blocks for simpler answer.

Solution 2:[2]

If you are trying to write code that will not crash on a divide by 0 exception, you should consider using try-catch statement. This would look something like this

try {
    divide(num1, num2); // method that divides values
} 
catch (DivideByZeroException) {
   /* exception handling code here */
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Said
Solution 2 Kallen Murphy