Sunday, September 29, 2013

P2C2: Write a program in C Sharp to check whether a number entered by a user is even or odd.

//Using if else statement

using System;

public class Program_Even_Odd
{
   public static void Main()
    {
        int num;

        Console.WriteLine("Enter any number: ");
        num = Convert.ToInt32(Console.ReadLine());

        if (num % 2 == 0)
            Console.WriteLine("\n{0} is an Even number", num);
        else
            Console.WriteLine("\n{0} is an Odd number", num);
                 
        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();

    }
}

OUTPUT:

Enter any number:
100

100 is an Even number

Press any key to exit...
---------------------------------------------------------------------------------------------

//Using case statement

using System;

public class Program_Even_Odd
{
   public static void Main()
    {
        int num, ans;

        Console.WriteLine("Enter any number: ");
        num = Convert.ToInt32(Console.ReadLine());

       ans = (num % 2);

       switch (ans)
       { 
           case 0:
               Console.WriteLine("\n{0} is an Even number", num);
               break;

           case 1:
               Console.WriteLine("\n{0} is an Odd number", num);
               break;

           default:
               Console.WriteLine("Invalid Entry");
               break;
       }
                   
        Console.WriteLine("\nPress any key to exit...");
        Console.ReadLine();

    }
}

OUTPUT:

Enter any number:
55

55 is an Odd number


Press any key to exit...

No comments:

Post a Comment