Calculating min and max of a 2-dimensional array in c

This program is to calculate the sum, min and max of the sum of the elements of an array. The
maximum value is a problem, it is always wrong.

void main(void)
{
    int  degree[3][2];
        int min_max[][];
    int Max=min_max[0][0];
    int Min=min_max[0][0];
    int i,j;
    int sum=0;

    clrscr();
    for(i=0;i<3;i++)
    {
        for(j=0;j<2;j++)
        {
            printf("\n enter degree of student no. %d in subject %d:",i+1,j+1);
            scanf("%d",&degree[i][j]);
        }

    }


    for(i=0;i<3;i++)
    {
        for(j=0;j<2;j++)
        {
            printf("\n Student no. %d degree in subject no. %d is %d",i+1,j+1,degree[i][j]);

        }

    }


    for(i=0;i<3;i++)
    {
        sum=0;
        for(j=0;j<2;j++)
        {
            sum+=degree[i][j];

        }
        printf("\n sum of degrees of student no. %d is %d",i+1,sum);
        min_max[i][j]=sum;
        if(min_max[i][j] <Min)
        {
            Min=min_max[i][j];
        }
        else if(min_max[i][j]>Max)
        {
            Max=min_max[i][j];
        }




    }
    printf("\nThe minimum sum of degrees of student no. %d is %d",i,Min);
    printf("\nThe maximum sum of degrees of student no. %d is %d",i,Max);
    getch();

}

      

+2


a source to share


2 answers


The problem is that you are initializing Min and Max to min_max [0] [0] before assigning any min_max values, so their contents are actually undefined.



Place appointments Min=min_max[0][0]

and Max=min_max[0][0]

AFTER calls scanf

.

+1


a source


Lines

printf("\nThe minimum sum of degrees is %d",i,Min);
printf("\nThe maximum sum of degrees  is %d",i,Max);

      

will print a single value i

, not Min

or Max

. Try this instead:

printf("\nThe minimum sum of degrees for %d is %d",i,Min);
printf("\nThe maximum sum of degrees for %d is %d",i,Max);

      



Line

min_max[i][j]=sum;

      

will always have a value of 2 for j

because it is outside the loop for

. Also, I don't understand why you want to store the partial sum of degrees in the min_max array?

0


a source







All Articles