Program to Check Whether a Number is Even or Odd - (C# Basic Programs)
Checking whether a number is even or odd is a basic programming exercise that is frequently asked in job interviews. In this tutorial, we'll discuss a program to check whether a number is even or odd using C# programming language.
Syntax
The syntax for checking whether a number is even or odd using C# is as follows:
if (number % 2 == 0) {
Console.WriteLine("{0} is even.", number);
} else {
Console.WriteLine("{0} is odd.", number);
}
Here, we are checking if the remainder of the number divided by 2 is equal to 0. If it is, then the number is even, otherwise it is odd.
Example
using System;
class Program {
static void Main(string[] args) {
int number;
Console.Write("Enter a number: ");
number = int.Parse(Console.ReadLine());
if (number % 2 == 0) {
Console.WriteLine("{0} is even.", number);
} else {
Console.WriteLine("{0} is odd.", number);
}
}
}
Output:
Enter a number: 7
7 is odd.
Explanation
In this program, we are first prompting the user to enter a number. Then, we are using the modulus operator to check if the remainder of the number divided by 2 is equal to 0. If it is equal to 0, then the number is even, and we output a message confirming it. Otherwise, the number is odd, and we output a message confirming that.
Use
Checking whether a number is even or odd is an elementary programming exercise that can be utilized in various applications. It can be used in mathematical and scientific calculations, statistical analysis, or in more complex logical operations that require determining whether numbers are even or odd.
Summary
In this tutorial, we discussed a program to check whether a number is even or odd using C# programming language. We covered the syntax, an example, explanation, use, and summary of the program. Checking whether a number is even or odd is a fundamental programming task, and its knowledge is essential for beginners learning to code in any programming language.