HI WELCOME TO SIRIS

C# program to print even numbers

Leave a Comment
This is a sample C# program to print even numbers. There are 2 ways to to print even numbers.
1. Start at Zero. Increment the value by 2, print it. Do this until you reach your target number.
2. Start at Zero. Divide the number by 2. If the remainder is zero, then you know the number is even. So print it and then increment it by 1 and divide the number by 2 again. Repeat this until we reach our target number.


This program can also be used to print odd numbers by making a minor logic change. Initialize the targetNumber variable to 1 instead of 0. If you are using dividing logic, then print the number if the remainder is not zero. 


Note: This program will crash and throws an exception, if you enter a very big number or a string. To handle exceptions, we can make use of try catch blocks. We will look at this in another program.
using System;
namespace SamplePrograms
{
    class EvenNumbers
    {
        public static void Main()
        {
            // Prompt the user to enter a target number. Target number is the 
            // number untill which the user want to have even and odd numbers printed
            Console.WriteLine("Please enter your target");


            // Declare a variable to hold the target number
            int targetNumber = 0;


            // Retrieve, Convert and store the target number
            targetNumber = Convert.ToInt32(Console.ReadLine());


            // Use a FOR or WHILE loop to print the even numbers, until our target number
            for (int i = 0; i <= targetNumber; i = i + 2)
            {
                Console.WriteLine(i);
            }


            // You can also check if a number is even, by dividing it by 2.
            //for (int i = 0; i <= targetNumber; i++)
            //{
            //    if ((i % 2) == 0)
            //    {
            //        Console.WriteLine(i);
            //    }
            //}


            // You can also use a while loop to do the same as shown below.
            //int start = 0;
            //while (start <= targetNumber)
            //{
            //    Console.WriteLine(start);
            //    start = start + 2;
            //}

            // This line is to make the program wait for user input, instead of immediately closing
            Console.ReadLine();

        }
    }

}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.