sai_985
sai_985

Reputation: 3

How to compare a two-dimensional array with a single-dimensional array in c?

I am hoping to compare two array and print two scores.

In the case below, should be 1 and 5 but I got 6488164 and 7536740. (as the first one only 7 is bigger than 4 and the next row is everything bigger)

Is it possible to compare a two-dimensional array with a single array and create an array with it? What did I do wrong or what should I do in order to do the comparison?

#include<stdio.h>
#include<stdlib.h>

int 
main(int argc, char *argv[]) {
	int mm_avg[2][5] = {{1,2,3,7,4},{2,3,4,5,7}};
	int lt_avg[5]={1,2,3,4,5};
	int i, j, score[100];
	
	for (i=0; i<5; i++){
		for (j=0; j<2; j++){
			if(mm_avg[j][i]>lt_avg[i]){
					score[j]++;
			}
		}
	}
	
	for (j=0; j<2; j++){
		printf("%d\n", score[j]);
	}
	return 0;
}
	

Upvotes: 0

Views: 833

Answers (2)

Dylan Scott
Dylan Scott

Reputation: 11

In C/C++, integers that are not initialized have an undefined value. Unlike say for instance, Java, which will assign a default value of 0 to an integer. In general it is good practice to always explicitly initialize your objects when declared.

#include<stdio.h>
#include<stdlib.h>

main(int argc, char *argv[])
{
    int mm_avg[2][5] = {{1,2,3,7,4},{2,3,4,5,7}};
    int lt_avg[5]={1,2,3,4,5};
    int i, j, score[2];

    for(int ndx = 0; ndx < 2; ++ndx)
    {
        score[ndx] = 0;
    }

    for (i = 0; i < 5; ++i)
    {
        for (j = 0; j < 2; ++j)
        {
            if(mm_avg[j][i] > lt_avg[i])
            {
                    /*printf("%d\n", j);
                    printf("%s", "mm_avg: ");
                    printf("%d\n", mm_avg[j][i]);
                    printf("%s", "lt_avg: ");
                    printf("%d\n", lt_avg[i]);
                    */
                    score[j]++;
            }
        }
    }

    for (j=0; j<2; j++)
    {
        printf("%d\n", score[j]);
    }
    return 0;
}

Upvotes: 1

Phil M
Phil M

Reputation: 1619

The score array is not initialized, so all 100 values in the array are just whatever happens to be lying around in memory.

Try int i, j, score[100] = {0};. This will initialize all 100 values to 0.

Upvotes: 1

Related Questions