Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Make a C# function?

which returns the average of all elements in a 2D array!

Signature of function is:

int AvgAoA(int [][]array);

1 Answer

Relevance
  • Jeremy
    Lv 6
    5 years ago

    First, ask your teacher why you'd want an average function to return an integer. That seems like a poor decision. Rarely would you end up with an average that worked out to a whole number. Wouldn't you'd want it to be:

    double AvgAoA(int [][]array);

    Anyway, I'll work on that premise that your average shouldn't be an integer. On to the function itself. Simply use the SelectMany to make the 2D array elements into a 1D one, and average that:

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Windows.Forms;

    namespace _2DAverage

    {

    public partial class Form1 : Form

    {

    public Form1()

    {

    InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)

    {

    int[][] a = { new[] { 1, 2 }, new[] { 5 }, new[] { 9, 8, 7, 6 } };

    MessageBox.Show(AvgAoA(a).ToString());

    }

    double AvgAoA(int[][] array)

    {

    int[] flattenedArray = array.SelectMany(a => a).ToArray();

    return flattenedArray.Average();

    }

    }

    }

Still have questions? Get your answers by asking now.