C# even or odd
Coding in practice
In C#, to determine if a number is even or odd, you can use the modulo operator (%). This operator returns the remainder of a division operation.
Here's how it works:
- If a number divided by 2 has a remainder of 0, the number is even.
- If a number divided by 2 has a remainder of 1, the number is odd.
The provided C# code functions as follows:
- An integer variable, number, stores the user's input.
- Console.WriteLine() prompts the user to input a number.
- Console.ReadLine() reads the input as a string.
- Convert.ToInt32() converts the string input into an integer.
- The if (number % 2 == 0) statement checks if dividing number by 2 results in a remainder of 0.
- If the condition is true (remainder is 0), a message indicating an even number is printed.
- If the condition is false (remainder is not 0), a message indicating an odd number is printed.
This code uses the modulo operator to determine if a number is even or odd in C#. The code can be modified to return a boolean value (true for even, false for odd) or perform other actions based on the outcome.
using System;
public class NumberCheck
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:"); // Prompt the user for input
int number = Convert.ToInt32(Console.ReadLine()); // Read and convert the input to an integer
if (number % 2 == 0) // Check if the remainder when divided by 2 is 0
{
Console.WriteLine($"{number} is an even number"); // Print that the number is even
}
else
{
Console.WriteLine($"{number} is an odd number"); // Print that the number is odd
}
}
}
Code 1 - Check number
Related articles
Curso básico de C# com aulas grátis
10 aulas gratuitas para você que quer aprender uma
Explorando MCP Server para .NET Developers
Para .NET Developers: Model Context Protocol
ecode10 subscription
Membership $1/mo
✓ Read full articles ✓ Read/write forums ✓ Access podcast ✓ Access full jobs opportunities (+288) ✓ Access eBooks ✓ Access magazine ✓ Access videos |
Subscribe now $1/mo |
Free
✓ Read open articles x Read/write forums ✓ Access podcast x Access full jobs opportunities (+288) x Access eBooks x Access magazine x Access videos |