Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • 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.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • 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:
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.
 
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!
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom