C# Lesson 2: Odd/Even Numbers with if Statement

In this program, we would like that

  1. The console window requests a number from the user.
  2. The program check if it is an even or odd number.
  3. 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
  1. Integers can be stored and manipulated in C# using the int data type.
  2. Use Convert.ToInt32(string) to convert the string into the int type of 32 bit size.
  3. 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.
  4. else statement is used to sun code when conditions of the if statements are not met (false).
  5. 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

Popular posts from this blog

C# Lesson 3: C# While Loop

C# Programming, Lesson 0: Installing Visual Studio