In: Computer Science
3. (Even or Odd) Write method IsEven that uses the remainder operator (%) to determine whether an integer is even. The method should take an integer argument and return true if the integer is even and false otherwise. Incorporate this method into an application that inputs a sequence of integers (one at time) and determines whether each is even or odd. (C# please)
Create a new C# console application with the name EvenOddApp add the below code in Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EvenOddApp
{
class Program
{
static void Main(string[] args)
{
bool repeat = true;
string n;
int num;
bool isEven;
do
{
//prompt and read a number or q to quit
Console.Write("\nEnter a integer [or q to quit]: ");
n = Console.ReadLine();
//if n is an integer store it in num
bool isInteger = Int32.TryParse(n, out num);
//if the user entered a number
if (isInteger)
{
//call IsEven method and check wether it is even or odd
isEven = IsEven(num);
//print wether the number is even or not
if (isEven)
Console.WriteLine("\n" + num + " is an even number");
else
Console.WriteLine("\n" + num + " is an odd number");
}
//if user didnot enter integer
else
{
//check if user entered q
if(n.ToLower()=="q")
repeat = false; //if yes exit the loop and quit the program
else
Console.WriteLine("\nInvalid input. Try again..."); //else print
invalid input
}
} while (repeat);
Console.WriteLine("\nPress any key to exit...");
Console.ReadLine();
}
//method IsEven and checks whether a number is even or odd
public static bool IsEven(int n)
{
//check if n leves a remainder 0 when divided by 2
if (n % 2 == 0)
return true; //if yes its eve, return true
else
return false; //else return false
}
}
}
Output: