• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.
    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C# C# Check if a number is even or odd

D

Deleted member 613

Guest
C#:
using System;
class MainClass {
  public static void Main (string[] args) {

int i;
            Console.Write("Enter a Number : ");
            i = int.Parse(Console.ReadLine());
            if (i % 2 == 0)
            {
                Console.Write("Your number is an Even Number :)");
                Console.Read();
            }
            else
            {
                Console.Write("Your number is an Odd Number :0");
            }

}
}

The console reads whichever number the user inputs and stores it in a variable(i). Then the computer does a check on the number(its to hard to explain exactly how) and then outputs a message corresponding to the result of the check.
 
Last edited by a moderator:

Mandiux

New Coder
Great example. The modulo operator in line 8 returns the remainder of variable 'i' divided by 2.
Modulo operator divides the two numbers, but ALWAYS returns the remainder.
In the case of an even number the remainder is always zero, otherwise the number is odd.
 

Trilient

New Coder
Very clean and easy to read example, thanks! You could expand even further to check the input of "i" to make sure it is a number and not a string, as well as only a whole number instead of floating points.

Great example. The modulo operator in line 8 returns the remainder of variable 'i' divided by 2.
Modulo operator divides the two numbers, but ALWAYS returns the remainder.
In the case of an even number the remainder is always zero, otherwise the number is odd.

Modulo is fun for a lot of mathematical nonsense in programming. Be sure to experiment and don't be afraid to break stuff!
 
Top