Check Whether a Number is Even or Odd with C#

Hi there,

The problem of checking whether a given number is even or odd is a common programming task. The modulus operator (%) in C# can be used to determine whether a number is even or odd. When an even number is divided by 2, the remainder is 0. If it is odd, the remainder is 1. As a result, if the number% 2 equals zero, the number is even; otherwise, it is odd.

Source Code:

namespace CccnaPoint
{
    class BasicPrograms
    {
        static void Main(string[] args)
        {
            // Declare a variable named "enumber" of type integer
            int enumber;

            // Prompt the user to enter a number and read the input from the console
            Console.WriteLine("Enter a number");
            enumber = int.Parse(Console.ReadLine());

            // Check if the entered number is even or odd
            if (enumber % 2 == 0)
            {
                // If the number is even, print a message indicating that it is even
                Console.WriteLine("You entered {0} and it's an even number", enumber);
            }
            else
            {
                // If the number is odd, print a message indicating that it is odd
                Console.WriteLine("You entered {0} and it's an odd number", enumber);
            }
        }
    }
}

Explanation:

This C# program determines whether a user-entered number is even or odd.

The program begins with a namespace declaration, CccnaPoint, which groups together related classes. There is a BasicPrograms class declaration within the namespace that contains the Main method.

The Main method is the program’s entry point, and it begins by declaring an integer variable called enumber. This variable will hold the number entered by the user.

The program then prompts the user to enter a number using the Console.

The statement WriteLine. The Control Panel. The ReadLine method reads from the console and saves it as a string. This string is converted to an integer and assigned to the enumber variable by the int.Parse method.

The program then uses the % operator to determine whether enumber is evenly divisible by two. If the remainder is zero, the number is even, and a message is displayed to indicate this. If the remainder is greater than zero, the number is odd, and a different message is printed to indicate this.

The program concludes with the closing curly braces for the Main method and the BasicPrograms class.

Overall, this program demonstrates how to use C# to read user input, perform a calculation, and display the result.

Leave a Reply

Your email address will not be published. Required fields are marked *