views:

209

answers:

2

This program to calculate sum,min and max of the sum of array elements
Max value is the problem, it is always not true.

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();

}
+1  A: 

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

Put the assignments Min=min_max[0][0] and Max=min_max[0][0] AFTER the scanf calls.

nico
A: 

The lines

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

will print the only value of 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);

The line

min_max[i][j]=sum;

will always have a value of 2 for j because it is outside of the for loop. Also, I'm not clear why you would want to store the partial sum of degrees in the min_max array?

Jacob
i want to store the partial sum of degrees in the min_max array because i want to have the min and max of sum of degrees
m2010
Then there is no reason to define the min_max array in the code you wrote; min_max[i][j] is currently ONLY used as a copy of `sum`.
Jacob
yesDo u mean i should write if (sum<min){min=sum;}if so, what is the initial value of min and max will be.
m2010
Initial value for Max can be 0, initial value for Min can be something large like 2000000000.
Jacob