C# Lesson 2: Odd/Even Numbers with if Statement
In this program, we would like that
- The console window requests a number from the user.
- The program check if it is an even or odd number.
- Result is printed out in the console window.
Let code the following (code in copy-able text at the bottom)
Press F5 to run the program...
Let us now analyze the code
- Integers can be stored and manipulated in C# using the int data type.
- Use Convert.ToInt32(string) to convert the string into the int type of 32 bit size.
- if statement is used to decide execution of code based on predefined conditions. The first block of code after if statement is run if the conditions are true.
- else statement is used to sun code when conditions of the if statements are not met (false).
- Modulus gives us the remainder of division and we use "%" to get the modulus in C#.
Here is the code in copy-able text
-----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyApp1
{
class Program
{
static void Main(string[] args)
{
// write to the console window
Console.Write("Hello, input a number: ");
// capture user input as string and store in variable called st
string st =Console.ReadLine();
int num = Convert.ToInt32(st);
// check the number
string result;
// use modulus % to get the remainder after division
// use == to check equality and return true/false
if (num % 2 == 0)
result = "even";
else
result = "odd";
// write to the console window
Console.WriteLine("Your number is "+result);
// read line from user to avoid auto-window closure
Console.ReadLine();
}
}
}
-----
Comments
Post a Comment