Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to find whether the Number is Divisible by 2
A number is divisible by 2 if the remainder is 0 when the number is divided by 2. This is checked using the modulo operator (%) in C#, which returns the remainder of a division operation.
Numbers divisible by 2 are called even numbers, while numbers not divisible by 2 are called odd numbers.
Syntax
Following is the syntax for checking divisibility by 2 using the modulo operator −
if (number % 2 == 0) {
// number is divisible by 2 (even)
} else {
// number is not divisible by 2 (odd)
}
Using if-else Statement
Let's check if the number 5 is divisible by 2 using an if-else statement −
using System;
class Program {
static void Main(string[] args) {
int num = 5;
// checking if the number is divisible by 2 or not
if (num % 2 == 0) {
Console.WriteLine(num + " is divisible by 2");
} else {
Console.WriteLine(num + " is not divisible by 2");
}
}
}
The output of the above code is −
5 is not divisible by 2
Using Ternary Operator
We can also use the ternary operator for a more concise approach −
using System;
class Program {
static void Main(string[] args) {
int num = 8;
string result = (num % 2 == 0) ? "divisible by 2" : "not divisible by 2";
Console.WriteLine(num + " is " + result);
}
}
The output of the above code is −
8 is divisible by 2
Checking Multiple Numbers
Here's an example that checks multiple numbers for divisibility by 2 −
using System;
class Program {
static void Main(string[] args) {
int[] numbers = {12, 7, 20, 15, 100};
Console.WriteLine("Checking divisibility by 2:");
foreach (int num in numbers) {
if (num % 2 == 0) {
Console.WriteLine(num + " is even (divisible by 2)");
} else {
Console.WriteLine(num + " is odd (not divisible by 2)");
}
}
}
}
The output of the above code is −
Checking divisibility by 2: 12 is even (divisible by 2) 7 is odd (not divisible by 2) 20 is even (divisible by 2) 15 is odd (not divisible by 2) 100 is even (divisible by 2)
How It Works
The modulo operator % calculates the remainder when one number is divided by another. When we divide any number by 2:
-
If the remainder is 0, the number is completely divisible by 2 (even number)
-
If the remainder is 1, the number leaves a remainder when divided by 2 (odd number)
Conclusion
Checking if a number is divisible by 2 in C# is accomplished using the modulo operator %. If number % 2 == 0, the number is even and divisible by 2; otherwise, it's odd and not divisible by 2.
