Latest Post

Monday, 2 January 2017

How to print sum of even numbers from 1 to N numbers[C#]

Write a program in C# to print sum of even numbers from 1 to N numbers.

Following is the simple C# code :

class Lab
    {
        static void Main(string[] args)
        {
            int i, number, sum = 0;
            Console.Write("\nEnter the Number whose even number you want: ");
            number = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\nall even number between 1 to {0} are ", number);
            for (i = 2; i <= number; i += 2)
            {
                sum += i;
                Console.WriteLine("\neven number= {0} ", i);
            }

            Console.WriteLine("\n Sum of all even number between 1 to {0} = {1}", number, sum);
            Console.ReadLine();
        }
    }

Output:-

Enter the Number whose even number you want: 20

all even number between 1 to 20 are

even number= 2

even number= 4

even number= 6

even number= 8

even number= 10

even number= 12

even number= 14

even number= 16

even number= 18

even number= 20

 Sum of all even number between 1 to 20 = 110


Government Jobs