'I'm new to C#, I tried to write a program that checks if the number entered by the user is prime or not, and I got this error after running it
The eroor is :Exception Unhadled :System.DivideByZeroException: 'Attempted to divide by zero.'And this is the code :
Console.Write("Enter the number: ");
int A =Convert.ToInt32(Console.ReadLine());
bool flag = false;
if (A < 2)
{
Console.WriteLine($"{A} is a prime number!! ");
}
for (int i = 0; i < A; i++)
{
if (A % i == 0)
{
flag = true; break;
}
}
if (flag == true)
{
Console.WriteLine($"{A} is not a prime number!!");
}
else
{
Console.WriteLine($"{A} is a prime number !!");
}
Console.ReadKey();
Solution 1:[1]
A % 0 will generate a DivideByZeroException. Start your loop with i = 1.
Solution 2:[2]
First A % 0 will report an exception, set i=0 to i=1, if you want to get specific exception information, wrap it in the "try...catch" code block
try{
for (int i = 1; i < A; i++)
{
if (A % i == 0)
{
flag = true; break;
}
}
}catch(Exception ex){
Console.WriteLine("Exception caught: {0}", ex);
}
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 | Damien Vande Kerckhove |
| Solution 2 |
