Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i need some help
Whats the best method for this question:

Write a program to check whether a number input by the user is even or odd?

Here is what i have done so far (Not Much)

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AS15_Number_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please Enter Me A Number : ");
            string str = Console.ReadLine();
            int num1 = Convert.ToInt16(str);


        }
    }
}


Please Help ASAP Thank You.
Posted
Comments
Pheonyx 5-Apr-13 5:25am    
This sounds very much like homework. And from your namespace it looks like homework!
We are not here to do it for you.

I will ask you a simple question: forgetting computer code, how can you test if a number is odd or even?

Hi,

Use the modulo operator %[^]:
C#
if ((num1 % 2) == 0)
{
    Console.WriteLine("even");
}
else
{
    Console.WriteLine("odd");
}

Hope this helps.
 
Share this answer
 
v2
Hi,

Though I am providing you with the solution.Please google for such simple stuff.

C#
using System;

using System.Collections.Generic;

using System.Text;



namespace OddEven

{

   class OddOREven

   {

      static bool ReadInteger(out int n)

      {

         string input = System.Console.ReadLine();

         n = 0;

         try

         {

            n = Convert.ToInt32(input);

            return true;

         }

         catch (System.Exception ex)

         {

            System.Console.WriteLine("Error in the input format\n\n");

            return false;

         }

      }

      static void Main(string[] args)

      {

         System.Console.Write("Enter a Number to Check ODD or EVEN: ");

         int number = 0;

         ReadInteger(out number);



         if((number % 2) == 0)

            System.Console.WriteLine("{0} is an EVEN number", number);

         else

            System.Console.WriteLine("{0} is an ODD number", number);

      }

   }

}
 
Share this answer
 
You can check if a number is even by:

C#
bool isEven = (number % 2) == 0


or for odd:
C#
bool isOdd = (number % 2) == 1


and for zero:
C#
bool isZero = (number == 0);


you can also combine that to:
C#
var result = number==0 ? "zero" : number%2 == 0 ? "even" : "odd";
Console.WriteLine(result);

(if you don't know "?:" --> Ternary Operation[^])
 
Share this answer
 
Comments
Thomas Daniels 5-Apr-13 5:44am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900