Advertisement
jyoung12387

Arrays - Calculating average of an array

Feb 17th, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2.  
  3. namespace random
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             int[] studentsGrades = new int[] { 15, 13, 8, 12, 6, 16 };
  10.             double averageResult = GetAverage(studentsGrades);
  11.            
  12.             foreach( int grade in studentsGrades)
  13.             {
  14.                 Console.WriteLine(grade);
  15.             }
  16.  
  17.             Console.WriteLine($"\nThe average is: {averageResult}");
  18.             Console.ReadLine();
  19.  
  20.             // Output:
  21.             // "15, 13, 8, 12, 6, 16"
  22.             // "The average is 11.66666666"
  23.  
  24.         }
  25.  
  26.         // Method to calculate average for the array of numbers.
  27.         static double GetAverage(int[] gradesArray)
  28.         {
  29.             int size = gradesArray.Length;
  30.             double average;
  31.             int sum = 0;
  32.  
  33.             for(int i = 0; i < size; i++)
  34.             {
  35.                 sum += gradesArray[i];
  36.             }
  37.  
  38.             average = (double) sum / size;
  39.             return average;
  40.         }
  41.  
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement