Array 2D

hello guys. i cant count the sum of milk. Please help me.

#include<iostream>
using namespace std;

int main()
{
const int the_number_rows=4;
const int the_number_columns=8;
int i,j,sum;
int matrix[the_number_rows][the_number_columns];

cout<<"The taste test of flavour."<<endl;
cout<<"1=very poor"<<endl;
cout<<"2=poor"<<endl;
cout<<"3=average"<<endl;
cout<<"4=good"<<endl;
cout<<"5=very good"<<endl;

cout<<endl;

for(i=0 ; i<the_number_rows ;i++)
for(j=0; j<the_number_columns ; j++)
matrix[the_number_rows][the_number_columns]=0;

for( i=0 ; i<the_number_rows ; i++ )
1
2
3
4
5
6
7
8
9
10
{	
		{
			cout<<"input scores for milk flavour  "<<i+1-1<<"  :  ";
		}
	
		for( j=0 ; j<the_number_columns ; j++)
		{
			cin>>matrix[i][j];
		}
	}


cout<<endl;

for( i=0 ; i<the_number_rows ; i++ )
{
1
2
3
4
5
6
7
8
9
{
			cout<<"\nMilk "<<i+1-1<<" "<<" : ";
			sum=0;
		}
		for( j=0 ; j<the_number_columns ; j++)
		{
			sum=sum+matrix[0][j];
			cout<<" "<<sum<<" ";
		}

}


return 0;
}
Can you format better your source?
You have a big problem: you are accessing a position of an array that does not belong actually to the array. In fact, you first declare a 2D array using this syntax:

int matrix[the_number_rows][the_number_columns];

Note that

1
2
    const int the_number_rows=4;
    const int the_number_columns=8;


So you have an array 4x8, but at some point in your code, you are accessing the position 8 of the 2D array, but that position does not exist, since arrays in C++ start being indexed by 0:

1
2
3
    for(i=0 ; i<the_number_rows ;i++)
        for(j=0; j<the_number_columns ; j++)
            matrix[the_number_rows][the_number_columns]=0;


In the line you are executing, you are basically accessing the 4th row and the 8th column, which are not part of the array:

matrix[4][8]=0;

Should be

matrix[3][7]=0;

But I suppose you want to initialise you array elements to 0, so your logic is still incorrect, it should be like this:

1
2
3
    for(i=0 ; i<the_number_rows ;i++)
        for(j=0; j<the_number_columns ; j++)
            matrix[i][j]=0;



I don't know if you have other problems in your code, but this should already fix a lot of problems.
Last edited on
Topic archived. No new replies allowed.