Blogger Widgets

Total Page visits

Wednesday, April 24, 2013

average of first n natural numbers and assign it to output1.If list contain any negative number, assign -1 to output1.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace sample
{
    class avg
    {
        public static void Main(string[] args)
        {
            avg a1 = new avg();
            int output = a1.avg1(7);
            Console.WriteLine("output is:{0}", output);
            Console.ReadLine();


        }

        int avg1(int x)
        {
            int sum = 0;
            if (x < 0)
            {
                return -1;
            }
            else
            {
                for (int i = 0; i <= x; i++)
                {
                    sum = sum + i;
                }
                return sum / x;
            }
        }
    }
}

No comments: