Latest Post

Monday, 2 January 2017

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

Write a program in C# to print sum of odd 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 odd number you want: ");
            number = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\nall even number between 1 to {0} are ", number);
            for (i = 1; i <= number; i += 2)
            {
                sum += i;
                Console.WriteLine("\nOdd number= {0} ", i);
            }

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

Output:-

Enter the Number whose odd number you want: 20

all even number between 1 to 20 are

Odd number= 1

Odd number= 3

Odd number= 5

Odd number= 7

Odd number= 9

Odd number= 11

Odd number= 13

Odd number= 15

Odd number= 17

Odd number= 19

 Sum of all odd number between 1 to 20 = 100


Government Jobs