Friday, March 21, 2014

Array with Method_Ex_4 (Wk 8) Feb 24-28, 2014

Q: Write method to return the average of positive values.

 static void Main(string[] args)
        {
            int[] A = { 12, -5, -9, 3, 6, 19, -13, -22, 33, 1, -17, 29 };

            float result = AverageOfPositives(A);
            Console.WriteLine("Average of Positive is: {0:f2}", result);

            Console.ReadLine();
        }
        static float AverageOfPositives (int[] A)
        {
            float sum = 0;
            int counter = 0;
            for (int i = 0; i < A.Length; i++)
            {
                if (A[i] > 0)
                {
                    sum += A[i];
                    counter++;
                }
            }
            float avg = sum / counter;
            return avg;
        }
    }
}

No comments:

Post a Comment