This article of C# Program checks if a given integer is Odd or Even, we have used the Ternary Operator (?:) and also seen the use of try and catch block.
Explanation:
The user enters the number that needs to be check for odd or even numbers. Here the entered number is checked with i % 2 == 0
, that is if after the divisibility of an entered number by 2, the remainder is zero then it is an Even number but if the remainder is not zero then the entered number is an Odd number.
C# Program to check whether the entered Number is Even or Odd.
Source Code: C# odd or even program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | using System; public class EvenOdd { public bool isEven(int i) { return (i % 2 == 0); } } public class Program { public static void Main(string[] arg) { Console.WriteLine("Enter a number to check even or odd:"); var i = Console.ReadLine().ToString(); try { var n = int.Parse(i); EvenOdd obj = new EvenOdd(); Console.WriteLine(obj.isEven(n) ? "Number is Even" : "Number is Odd"); } catch (System.Exception ex) { Console.WriteLine("Invalid String Format!!"); } } } |
Output: