0

I'm having trouble with a program that takes a 2d array, calculates the average of each row, then stores these averages in a new array. Where I seem to be having the problem is with actually assigning the averages to the new 1d array. If I put a print statement in the loop directly after the value has been assigned it seems to be there and work fine. But once I try to display whats in the array with my created display function it is all zeroes except for one entry that's a random large number.

Sample Output:

36.25 58.00 52.00 42.00 51.75 47.00 <--- From print within average function (Correct)

0.000 0.000 0.000 0.000 406778500087808.000 0.000 <--- From created display function

void row_average(int vals2d[][4], int rows, int cols)
{
    int k, l, sum;
    float avg, rowavg[6];
    for (k=0; k<rows; k++){
        sum = 0;
        avg = 0;
        for (l=0; l<cols; l++){
            sum = sum + vals2d[k][l];
            avg = (float)sum/4;
        }
        rowavg[k] = avg;
        printf("%.2f  ", rowavg[k]);
    }
}

void array_1display(float rowavg[], int size)
{
    int m;
    for (m=0; m<size; m++){
        printf("%.3f  ", rowavg[m]);
    }
}

int main()
{
    float rowavg[6];
    int vals2d[6][4] ={
    {12,54,34,45},
    {68,76,65,23},
    {75,23,76,34},
    {6,45,58,59},
    {35,67,93,12},
    {66,90,25,7}
    };

    row_average(vals2d, 6, 4);
    printf("\n");
    array_1display(rowavg, 6);
}

1 Answer 1

1

You need to pass your array rowavg[] or make it global.

Here is some correction:

#include <stdio.h>

void row_average(int vals2d[][4], int rows, int cols, float rowavg[])
{
    int k, l, sum;
    float avg;
    for (k=0; k<rows; k++){
        sum = 0;
        avg = 0;
        for (l=0; l<cols; l++){
            sum = sum + vals2d[k][l];
            avg = (float)sum/4;
        }
        rowavg[k] = avg;
        printf("%.2f  ", rowavg[k]);
    }
}

void array_1display(float rowavg[], int size)
{
    int m;
    for (m=0; m<size; m++){
        printf("%.3f  ", rowavg[m]);
    }
}

int main()
{
    float rowavg[6];

    int vals2d[6][4] ={
            {12,54,34,45},
            {68,76,65,23},
            {75,23,76,34},
            {6,45,58,59},
            {35,67,93,12},
            {66,90,25,7}
        };

    row_average(vals2d, 6, 4, rowavg);
    printf("\n");
    array_1display(rowavg, 6);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much that solved my issue perfectly. Passing things into functions is still something that gives me a little grief and it looks like a have a little more reading to do.
ok, good luck! here is some good references, stackoverflow.com/questions/562303/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.