This program checks whether a number entered in a textbox is an Even or Odd number. In math, a number who can be divided by 2 with a zero reminder Is an Even number. If a number is not divided by 2 then that number is indeed an odd number.

This function is frankly easy to write, however it could be useful and can be used in your program whenever needed.

Let’s get started!

First, create a Visual Studio Windows Form Application in C#. Add a TextBox and Button to the main form.

Below is the function to check the Even and Odd number.

C#

   private int EvenOrOdd()
        {
            int number;

            number = int.Parse(txt.Text);

            if (number % 2 == 0)

            {
                // Returns 0 if Even
                return 0;

            }

            else

            {
                // Return 1 if Odd
                return 1;
            }
        }

Now call the function from the button click Event:

C#

        private void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (EvenOrOdd() == 0)
                {
                    MessageBox.Show(txt.Text + " is an Even Number");
                }
                else if (EvenOrOdd()==1)
                {
                    MessageBox.Show(txt.Text + " is an Odd Number");
                }
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }

The Result

 

Related Posts:

 

Last modified: March 6, 2019

Comments

Write a Reply or Comment

Your email address will not be published.