user3804846
user3804846

Reputation: 11

C++ Passing 2d arrays to functions

Understand to calculate average of array we need to declare a function below. to loop and read row by row.

double getAverage(int arr[], int size)
{
  int    i, sum = 0;       
  double avg;          

  for (i = 0; i < size; ++i){
    sum += arr[i];
   }

  avg = double(sum) / size;    
  return avg;
}

after that we will call the value to the main.

#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main ()
{
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;

   // output the returned value 
   cout << "Average value is: " << avg << endl; 

   return 0;
}

So my question is, what if i want to to calculate the average of row*col? am i going to declare something like this? let say the size for row and col is arr[3][6]

double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
    float sum=0, average;

    for (int i = 0 ; i < noOfrows ; i++) {
        for (int j = 0; j<noOfcol; j++) {    
        sum = sum + arr[i][j];    
        }
    }
        average = (float)sum / (float)(noOfcol*noOfrows);
        cout << "   " << average;

        return average; 
}

Here's my code

int main()
{   
    int sales[3][6] = {{1000, 800, 780, 450, 600, 1200},
                       {800, 900, 500, 760, 890, 1000},
                        {450, 560, 570, 890, 600, 1100}};

    int avg;

    int choice;//menu choice

    const int computeAverage_choice = 1,
              computeTotal_choice = 2,
              listMaxMin_choice = 3,
              Exit_choice = 4;

    do
    {   
            //displayMenu(); // Show Welcome screen
            choice = displayMenu();
            while (choice < 1 || choice > 4)
         {
               cout << "Please enter a valid menu choice: " ;
               cin >> choice;
         }

            //If user does not want to quit, proceed.
         if (choice != Exit_choice)
         {  

                    switch (choice)
                    {
                           case computeAverage_choice:
                                avg = computeAverage(sales, 3, 6);
                                cout<<"The averge:" << avg;

                                break;

                           case computeTotal_choice:
                                //reserves
                                break;

                           case listMaxMin_choice:
                                //reserves
                                break;
                    }
         }
         } while (choice != Exit_choice);
            return 0;
}

Upvotes: 0

Views: 247

Answers (4)

Jarod42
Jarod42

Reputation: 217105

As int sales[3][6] as the same layout than int sales[3 * 6], you may reuse your previous code and simply call

const double avg = getAverage(&sales[0][0], 3 * 6);

If you want to pass array, the best way is pass by reference (with a non intuitive syntax) and let template deduce size:

template <std::size_t R, std::size_t  C>
double getAverage(const int (&a)[R][C]) {
    return std::accumulate(&a[0][0], &a[0][0] + R * C, 0.) / (R * C);
}

Upvotes: 0

Vasuki Dileep
Vasuki Dileep

Reputation: 583

Your question is quite unclear to me. If you are worried about declaring the rows and columns and passing it to a function, you can do it by either passing the array as an argument or the pointer to an array as an argument. I have defined the rows and cols length in #define.

Definitions

#include <iostream>
using namespace std;
#define NO_OF_ROWS 2
#define NO_OF_COLS 3

Main Function

int main ()
{
// an int array with 5 elements
int balance[5] = {1000, 2, 3, 17, 50};
int ar[2][3] = {{5,5,5},{10,10,10}};
double avg, avgRC;

// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
avgRC = getAvg(ar);
// output the returned value 
cout << "Average value is: " << avg << endl; 
cout << "Average of row*col: " << avgRC << endl;

return 0;
}

GetAvg function that returns row*col average

double getAvg(int arr[][NO_OF_COLS])
{
 float sum=0, average;

   for (int i = 0 ; i < NO_OF_ROWS ; i++) {
    for (int j = 0; j<NO_OF_COLS; j++) {

    sum = sum + arr[i][j];

    }
 }
    average = (float)sum / (float)(NO_OF_ROWS*NO_OF_COLS);
    cout << "   " << average;
    return average; 

}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

"am i going to declare something like this?"

Yes. That's how you declare a function that takes an array of arrays of six int.

If the size isn't known there are two ways of solving it: Either use std::vector (or in the case of arrays of arrays, a vector of vectors). Or you can use templates for the array rows and columns:

template<size_t noOfrows, size_t noOfcol>
int getAverage(int const (&arr)[noOfrows][noOfcol])
{
    ...
}

That way you only need to call it with the array as argument, the number of rows and columns will be deduced by the compiler:

int balance1[4][7] = { ... };
int average1 = getAverage(balance1);

int balance2[2][5] = { ... };
int average2 = getAverage(balance2);

It will also work no matter the size of the arrays or the sub-arrays.

Upvotes: 0

CIsForCookies
CIsForCookies

Reputation: 12817

If your function is declared like so: double getAverage(int arr[][6], int noOfrows, int noOfcol) but you're trying to call it using avg = getAverage( balance, 5 ) ; [only 2 args] your compiler should return an error.

Just adjust your call to avg = getAverage( balance, 5 */num or rows*/ , 6 */num of cols*/) ;

#include <iostream>
using namespace std;

 double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
    float sum=0, average;

    for (int i = 0 ; i < noOfrows ; i++) {
        for (int j = 0; j<noOfcol; j++) {

        sum = sum + arr[i][j];

        }
    }
        average = (float)sum / (float)(noOfcol*noOfrows);
        cout << "   " << average;

        return average; 
}


 int main()
 {
    int a[2][6] = {{1,2,3,4,5,6},{2,3,4,5,6,7}};
    getAverage(a, 2, 6);   // OK
    getAverage( a, 5 ) ;   // compile error
    return 0;
 }

Upvotes: 1

Related Questions