settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How to check if a number is Even or Odd in C#?

+5 votes

I need to create a program which checks if a number (random one) is Even or Odd in Visual Studio. And prints the result

asked in C# category by user matthew44

4 Answers

+2 votes
 
Best answer

Check this code out:

using System;

class RandomNumberCheck
{
    static void Main()
    {
        Random rnd = new Random();
        int a = rnd.Next(0, 100);
        Console.WriteLine(a);

        if (a % 2==0)
        {
            Console.WriteLine("Even");
        }
        else
        {
            Console.WriteLine("Odd");
        }
    }
}

 

answered by user andrew
edited by user golearnweb
+2 votes

Another solution:

using System;

class OddOrEvenIntegers
{
    static void Main()
    {
        Console.WriteLine("Please write your number, so the expression can check whether it is odd or even:");
        int n = int.Parse(Console.ReadLine());

        bool result = n % 2 == 0;
        Console.WriteLine("Your number {0} is even? Answer: {1}", n, result);
    }
}
answered by user john7
edited by user golearnweb
+2 votes
using System;

    class EvenOrOdd
    {
        static void Main()
        {
            Console.WriteLine("Enter an integer number: ");
            int number = int.Parse(Console.ReadLine());
            bool check = number % 2 != 0;
            Console.WriteLine("Does the number is odd?");
            Console.WriteLine(check);
        }
    }
answered by user Jolie Ann
edited by user golearnweb
You can also check if a number is odd with this code:

number % 2 == 1
please, format your code properly!
+1 vote

Here is my solution with bool:

using System;

class Program
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        bool result = (n % 2 != 0 && n > 0);

        Console.WriteLine("Odd? {0}", result);
    }
}
answered by user hues
...