Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with multi-diemensional array

Status
Not open for further replies.

mnkjoi

Technical User
Nov 16, 2012
1
JO
Hello,

I have a problem with the following code

int main()
{
int i,j,max;
int a[3][3]={{85,99,77},
{80,73,74},
{89,33,88}};

for (i=0;i<3;i++){
max=0;
printf (" \n");
for (j=0;j<3;j++)
if (max<a[j])
max=a[j];
printf ("%d the maximum is %i ",a[j],max);
}
}

I want the output to be the ALL numbers in arrays and the maximum number of each row I tried and tried but I couldn't know where is the problem,and here is the output
80 the maximum is 99
89 the maximum is 80
0 the maximum is 99

any help pls
 
The 3rd line of your output is:
... is 89
(please, look at your program output again;)

It's a wrong way to get max row values: it does not work for negative values. Right way:
Code:
#define N 3
int maxval;
int a[N][N] = { ...
...
for (i = 0; i < N; ++i) {
    maxval = a[i][0];
    for (j = 1; j < N; ++j) {
        if (maxval < a[i][j])
            maxval = a[i][j];
    }
    printf("Row %d: maxval %d\n",i,maxval);
}
Yet another mistake: reference to i,j-th element after loop in printf call. Think: j == 3 after loop was terminated and you are trying to print incorrectly indexed array elements:
Code:
a[0][3] ... a[1][3] ... a[2][3]

Next time use CODE tag for your snippets. Press help (?) button on the posting form to get help on this forum TGML layout tags...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top