C# program to check if a number is divisible by 2
Here's a C# program to check if a number is divisible by 2:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (IsDivisibleByTwo(number))
{
Console.WriteLine($"{number} is divisible by 2.");
}
else
{
Console.WriteLine($"{number} is not divisible by 2.");
}
}
static bool IsDivisibleByTwo(int number)
{
return number % 2 == 0;
}
}
In this program, the IsDivisibleByTwo method takes an integer number as input and checks if it is divisible by 2. It uses the modulo operator % to calculate the remainder when number is divided by 2. If the remainder is 0, it means the number is divisible by 2, so the method returns true; otherwise, it returns false.
The Main method prompts the user to enter a number, calls the IsDivisibleByTwo method with the user input, and displays the appropriate message based on the result.
Note that the program assumes the user will input a valid integer. It doesn't handle exceptions if the input is not a valid integer.