So I have an assignment, and within it is a question that requires you to construct a 2D array with 5 rows and 4 columns, with each of them containing grades. The question requires you to determine how many grades are less than 60, between 60 and 70 and so on (till 100). Thing is when I try to search through it, there should only be 20 total grades, but my solution gives some far fetched number like 60,000 or whatever. I’m at a loss as to what is wrong with my code. I used two for loops to search through the array. Attached is what I’ve tried. Thanks a ton for any help
#include <stdio.h>
int main(){
double grades[5][4] = {
{69, 58, 95, 78},
{84, 75, 86, 32},
{75, 68, 65, 73},
{99, 54, 24, 88},
{65, 78, 84, 65}
};
int lessthan60, sixtyseventy, seventyeighty, eightyninety, greaterthan90;
for (int r = 0; r < 5; r++){
for (int c=0; c < 4; c++){
if (grades[r][c] < 60){
lessthan60++;
}
else if (grades[r][c] >=60 && grades[r][c] < 70){
sixtyseventy++;
}
else if (grades[r][c] >=70 && grades[r][c] < 80){
seventyeighty++;
}
else if (grades[r][c] >=80 && grades[r][c] < 90){
eightyninety++;
}
else{
greaterthan90++;
}
}
}
printf("Grades less than 60: %d\n", lessthan60);
printf("Grades between 60 and 70: %d\n", sixtyseventy);
printf("Grades between 70 and 80: %d\n", seventyeighty);
printf("Grades between 80 and 90: %d\n", eightyninety);
printf("Grades between 90 and 100: %d\n", greaterthan90);
return 0;
}
>Solution :
These variables having automatic storage duration
int lessthan60, sixtyseventy, seventyeighty, eightyninety, greaterthan90;
are uninitialized and have indeterminate values. You have to initialize them by zero explicitly
int lessthan60 = 0, sixtyseventy = 0, seventyeighty = 0, eightyninety = 0, greaterthan90 = 0;
Also if statements can be written simpler like
if (grades[r][c] < 60){
lessthan60++;
}
else if ( grades[r][c] < 70){
sixtyseventy++;
}
else if ( grades[r][c] < 80){
seventyeighty++;
}
else if ( grades[r][c] < 90){
eightyninety++;
}
else{
greaterthan90++;
}
Also instead of the magic numbers 4 and 5 it is better to use named constants as for example
enum { ROWS = 5, COLS = 4 };
double grades[ROWS][COLS] = {
{69, 58, 95, 78},
{84, 75, 86, 32},
{75, 68, 65, 73},
{99, 54, 24, 88},
{65, 78, 84, 65}
};
//...
for (int r = 0; r < ROWS; r++){
for (int c=0; c < COLS; c++){
//...