[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 200
  • Last Modified:

c++ 2 dimensional array

Hello, my simple code is not printing out the users correct values:
#include <iostream>
using namespace std;
void echo(int a[][5], int sizeOfarray);
int main(void)
{
const int col=4;
const int rows=5;

int a[col][rows];

for (int i =0; i<col; i++)
{
	for(int b=0; b<rows; b++)
	{
      cout <<"please enter in an number : ";
	  cin >> a[col][rows];
	  
	}

}
 
echo(a,5);

}
void echo(int a[][5], int sizeOfarray)
{
	for(int i =0; i < sizeOfarray; i++)
	{
		for(int index2=0; index2 <5; index2++)
		{
			cout <<a[i][index2] <<" ";
			cout <<endl;
		}

	}

}

Open in new window


0
businessesatoz
Asked:
businessesatoz
  • 2
  • 2
1 Solution
 
farzanjCommented:
Here is revised code.  
#include <iostream>
using namespace std;

const int col=2;
const int rows=2;
void echo(int a[][rows], int sizeOfarray);

int main(void)
{
    int a[col][rows];

    for (int i =0; i<col; i++)
    {
        for(int b=0; b<rows; b++)
        {
          cout <<"Please enter in a number : ";
          cin >> a[i][b];
        }

    }
    echo(a,5);
}


void echo(int a[][rows], int sizeOfarray)
{
    for(int i =0; i < col; i++)
    {
        for(int index2=0; index2 <rows; index2++)
        {
            cout <<a[i][index2] <<" ";
            cout <<endl;
        }

    }

}

Open in new window


The problem was that you were using col and rows in the input which is a constant.  So you were changing the same row over and over
0
 
farzanjCommented:
Also constants are kept global and this is typically the way it is done and there is on harm in doing so.

Since the rows and col are both constants, you don't need to pass the size of array.
0
 
businessesatozAuthor Commented:
Thanks i found my error.. i was trying to get a[cols][rows] when i should have been using my for loop variable i believe..
0
 
businessesatozAuthor Commented:
thank you..
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now