Passing 2D array to a Function in c++ - c++

I am Having Problem with Passing a 2D array to a c++ Function. The function is supposed to print the value of 2D array. But getting errors.
In function void showAttributeUsage(int)
Invalid types for int(int) for array subscript.
I know the problem is with the syntax in which I am passing the particular array to function but I don't know how to have this particular problem solved.
Code:
#include <iostream>
using namespace std;
void showAttributeUsage(int);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
int attVal[qN][aN];
cout << "\nEnter Attribute Usage Values" << endl;
for(int n = 0; n < qN; n++) { //for looping in queries
cout << "\n\n***************** COLUMN " << n + 1 << " *******************\n\n";
for(int i = 0; i < aN; i++) { //for looping in Attributes
LOOP1:
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if((attVal[n][i] > 1) || (attVal[n][i] < 0)) {
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
goto LOOP1; //if wrong input value
}
}
}
showAttributeUsage(attVal[qN][aN]);
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
getch();
return 0;
}
void showAttributeUsage(int att)
{
int n = 0, i = 0;
while(n != '\0') {
while(i != '\0') {
cout << att[n][i] << " ";
i++;
}
cout << endl;
n++;
}
}

I really suggest to use std::vector : live example
void showAttributeUsage(const std::vector<std::vector<int>>& att)
{
for (std::size_t n = 0; n != att.size(); ++n) {
for (std::size_t i = 0; i != att.size(); ++i) {
cout << att[n][i] << " ";
}
cout << endl;
}
}
And call it that way:
showAttributeUsage(attVal);

Looking at your code, I see no reason why you can't use std::vector.
First, your code uses a non-standard C++ extension, namely Variable Length Arrays (VLA). If your goal is to write standard C++ code, what you wrote is not valid standard C++.
Second, your initial attempt of passing an int is wrong, but if you were to use vector, your attempt at passing an int will look almost identical if you used vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
typedef std::vector<int> IntArray;
typedef std::vector<IntArray> IntArray2D;
using namespace std;
void showAttributeUsage(const IntArray2D&);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
IntArray2D attVal(qN, IntArray(aN));
//... Input left out ...
showAttributeUsage(attVal);
return 0;
}
void showAttributeUsage(const IntArray2D& att)
{
for_each(att.begin(), att.end(),
[](const IntArray& ia) {std::copy(ia.begin(), ia.end(), ostream_iterator<int>(cout, " ")); cout << endl;});
}
I left out the input part of the code. The vector uses [] just like a regular array, so no code has to be rewritten once you declare the vector. You can use the code given to you in the other answer by molbdnilo for inputing the data (without using the goto).
Second, just to throw it into the mix, the showAttributeUsage function uses the copy algorithm to output the information. The for_each goes throw each row of the vector, calling std::copy for the row of elements. If you are using a C++11 compliant compiler, the above should compile.

You should declare the function like this.
void array_function(int m, int n, float a[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0.0;
}
where you pass in the dimensions of array.

This question has already been answered here. You need to use pointers or templates. Other solutions exists too.
In short do something like this:
template <size_t rows, size_t cols>
void showAttributeUsage(int (&array)[rows][cols])
{
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}

You're using a compiler extension that lets you declare arrays with a size determined at runtime.
There is no way to pass a 2D array with such dimensions to a function, since all but one dimension for an array as a function parameter must be known at compile time.
You can use fixed dimensions and use the values read as limits that you pass to the function:
const int max_queries = 100;
const int max_attributes = 100;
void showAttributeUsage(int array[max_queries][max_attributes], int queries, int attributes);
int main()
{
int attVal[max_queries][max_attributes];
int qN = 0;
int aN = 0;
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
cout << "\nEnter Attribute Usage Values" << endl;
for (int n = 0; n < qN; n++)
{
cout << "\n\n***************** COLUMN " << n + 1 <<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad_input = true;
while (bad_input)
{
bad_input = false; // Assume that input will be correct this time.
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad_input = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal, qN, aN);
getch();
return 0;
}
void showAttributeUsage(int att[max_queries][max_attributes], int queries, int attributes)
{
for (int i = 0; i < queries; i++)
{
for (int j = 0; j < attributes; j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
For comparison, the same program using std::vector, which is almost identical but with no size limitations:
void showAttributeUsage(vector<vector<int> > att);
int main()
{
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
vector<vector<int> > attVal(qN, vector<int>(aN));
cout << "\nEnter Attribute Usage Values"<<endl;
for (int n = 0; n < qN; n++)
{
cout<<"\n\n***************** COLUMN "<<n+1<<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad = true;
while (bad)
{
bad = false;
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal);
getch();
return 0;
}
void showAttributeUsage(vector<vector<int> > att);
{
for (int i = 0; i < att.size(); i++)
{
for (int j = 0; j < att[i].size(); j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}

The Particular Logic worked for me. At last found it. :-)
int** create2dArray(int rows, int cols) {
int** array = new int*[rows];
for (int row=0; row<rows; row++) {
array[row] = new int[cols];
}
return array;
}
void delete2dArray(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
delete [] ar[row];
}
delete [] ar;
}
void loadDefault(int **ar, int rows, int cols) {
int a = 0;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
ar[row][col] = a++;
}
}
}
void print(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
cout << " | " << ar[row][col];
}
cout << " | " << endl;
}
}
int main () {
int rows = 0;
int cols = 0;
cout<<"ENTER NUMBER OF ROWS:\t";cin>>rows;
cout<<"\nENTER NUMBER OF COLUMNS:\t";cin>>cols;
cout<<"\n\n";
int** a = create2dArray(rows, cols);
loadDefault(a, rows, cols);
print(a, rows, cols);
delete2dArray(a, rows, cols);
getch();
return 0;
}

if its c++ then you can use a templete that would work with any number of dimensions
template<typename T>
void func(T& v)
{
// code here
}
int main()
{
int arr[][7] = {
{1,2,3,4,5,6,7},
{1,2,3,4,5,6,7}
};
func(arr);
char triplestring[][2][5] = {
{
"str1",
"str2"
},
{
"str3",
"str4"
}
};
func(triplestring);
return 0;
}

Related

array elements not printing when trying to print in the main function

I want to find the factors of a product by using arrays to check whether they equal it or not
the values do not print
here is the code
#include <iostream>
using namespace std;
int main() {
int arr[5] = { 1,3,5,7,2 };
int arr1[5] = { 0,6,5,4,9 };
int X;
cout << "Please enter X:"; cin >> X;
for (int i = 0, j = 0; i < 5 && j < 5; ++i, ++j) {
if (arr[i]*arr[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}
Use this nested loops
for (int i = 0; i < 5 ;++i) {
for(int j=0 ;j<5;++j){
if (arr[i]*arr1[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}

I need some assistance with creating a function

I am new, not that good with functions, and I am trying to solve this question:
Suppose A, B, C are arrays of integers of size [M], [N], and [M][N], respectively. The user will enter the values for the array A and B. Write a user defined function in C++ to calculate the third array C by adding the elements of A and B. If the elements have the same index number, they will be multiplied. C is calculated as the following: -
Use A, B and C as arguments in the function.
Below is my attempt at the problem.
#include<iostream>
using namespace std;
void Mix(int(&A)[], int(&B)[], int(&C)[][100], int N, int M);
//dont understand why you used Q
int main()
{
//variable declaration
int A[100], B[100], C[100][100], n, m, l = 0;
//input of size of elements for first ararys
cout << "Enter number of elements you want to insert in first array: ";
cin >> n;
cout << "-----------------" << endl;
cout << "-----------------" << endl;
cout << "Enter your elements in ascending order" << endl;
//input the elements of the array
for (int i = 0; i < n; i++)
{
cout << "Enter element " << i + 1 << ":";
cin >> A[i];
}
cout << endl << endl;
//input of size of elements for first ararys
cout << "Enter number of elements you want to insert in second array: ";
cin >> m;
cout << "-----------------" << endl;
cout << "-----------------" << endl;
cout << "Enter your elements in descending order" << endl;
//input the elements of the array
for (int i = 0; i < m; i++)
{
cout << "Enter element " << i + 1 << ":";
cin >> B[i];
}
Mix(A, B, C, n, m);
cout << "\nThe Merged Array in Ascending Order" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
{
cout << C[i][j] << " ";
}
cout << "\n"; //endline never use endl its 10 times slower
}
system("pause");
return 0;
}
void Mix(int(&A)[], int(&B)[], int(&C)[][100], int N, int M)
{
// rows is the index for the B array, cols is index for A array
int rows = 0;
int cols = 0;
while (rows < M) {
while (cols < N) {
if (rows == cols) { // remember ==
C[rows][cols] = B[rows] * A[cols];
}
else {
C[rows][cols] = B[rows] + A[cols];
}
cols++; // increment here
}
rows++; // increment here
}
return;
}
Here is an example of the output:
enter image description here
In order to make the C array two-dimensional, it needs to be expressed as C[100][100], instead of C[200]. That is the first step. Next, in your Mix() function, you need to cycle through each element of both A and B (ex. two for loops). Your rows change as B changes, and your columns change as A changes. Include a check for identical indices that will determine whether to add or multiply the two values together.
void Mix(int A[], int B[], int C[][], int N, int M) {
// rows is the index for the B array, cols is index for A array
for (int rows = 0; rows < M; rows++) {
for (int cols = 0; cols < N; cols++) {
if (rows == cols) { // remember ==
C[rows][cols] = B[rows] * A[cols];
} else {
C[rows][cols] = B[rows] + A[cols];
}
}
}
}
Make sure your arrays are properly defined and print out the C array by row and column to match the specifications.
UPDATE: If you want to use while loops, I would default to deconstructing the for loops and apply the same logic:
void Mix(int A[], int B[], int C[][], int N, int M) {
// rows is the index for the B array, cols is index for A array
int rows = 0;
int cols = 0;
while (rows < M) {
while (cols < N) {
if (rows == cols) { // remember ==
C[rows][cols] = B[rows] * A[cols];
} else {
C[rows][cols] = B[rows] + A[cols];
}
cols++; // increment here
}
rows++; // increment here
}
}
I would definitely recommend the for loop approach, as it is more compact, yet does the exact same operations.
There are a lot of things wrong with your code. First off an 2D array must be declared with 2 squared brackets so C[200][200]. In the Mix function the logical operator is == not = in if (A[I] = B[J])
Anyway here's the function that you need:
#include<iostream>
using namespace std;
void Mix(int A[], int B[], int C[], int N, int M) {
//dont understand why you used Q
int i, j;
for(i=0; i<N; i++) {
for(j=0; j<M; j++) {
if(i==j){
C[i][j] = A[i] * B[j];
}
else {
C[i][j] = A[i] + B[j];
}
}
}
return C[i][j];
}
int main()
{
//variable declaration
int A[100], B[100], C[200], j, i, n, m, l = 0;
string Comma;
//input of size of elements for first ararys
cout << "Enter number of elements you want to insert in first array: ";
cin >> n;
cout << "-----------------" << endl;
cout << "-----------------" << endl;
cout << "Enter your elements in ascending order" << endl;
//input the elements of the array
for (i = 0; i < n; i++)
{
cout << "Enter element " << i + 1 << ":";
cin >> A[i];
}
cout << endl << endl;
//input of size of elements for first ararys
cout << "Enter number of elements you want to insert in second array: ";
cin >> m;
cout << "-----------------" << endl;
cout << "-----------------" << endl;
cout << "Enter your elements in descending order" << endl;
//input the elements of the array
for (j = 0; j < m; j++)
{
cout << "Enter element " << j + 1 << ":";
cin >> B[j];
}
C = Mix(A, B, C, n, m);
cout << "\nThe Merged Array in Ascending Order" << endl;
for(i=0; i<n; i++) {
for(j=0; j<m; j++) {
cout<<C[i][j]<<" ";
}
cout<<"\n" //endline never use endl its 10 times slower
}
system("pause");
return 0;
}
Because M and N are defined at run time, you'll really want to use vectors to represent them. Additionally consider returning a 2D container so as to leverage return value optimization.
I'm going to write an example using a vector of vectors for simplicity (see What are the Issues with a vector-of-vectors? for more on why that's really just good for a toy example):
vector<vector<int>> Mix(const vector<int>& A, const vector<int>& B) {
vector<vector<int>> result(size(B), vector<int>(size(A)));
for(size_t i = 0U; i < size(B); ++i) {
for(size_t j = 0U; j < size(A); ++j) {
result[i][j] = A[j] * B[i];
}
}
return result;
}
Live Example
EDIT:
If you must use arrays you'll miss out on return value optimization. I'd only choose this as a good option in the situations:
That you weren't returning anything, in which case your function would probably look something like:
void Mix(const int* A, const int* B, const size_t size_A, const size_t size_B)
{
for(size_t i = 0U; i < size_B; ++i) {
for(size_t j = 0U; j < size_A; ++j) {
cout << '[' << i << "][" << j << "]: " << A[j] * B[i] << '\t';
}
cout << endl;
}
}
That you weren't calling a function and you'd already been given int A[M] and int B[N] as inputs and int C[N][M] as an output, in which case the code you'd inline would probably look something like this:
for(size_t i = 0U; i < size(B); ++i) {
for(size_t j = 0U; j < size(A); ++j) {
C[i][j] = A[j] * B[i];
}
}

Equivalence Relation

I am stuck on what to do next... The program is suppose to check to see if entered Zero-One Matrix is an Equivalence relation (transitive, symmetric, and reflexive) or not. I am still new to C++ (started this semester). I know how to create the matrix using vector but not on how to check if it is equivalence relation or not..
I assume I need to use boolean function but I'm stuck on what I need to put in as an argument or if this is correct. My original thought was... so for symmetric it will look like (which I know this goes after #include and beofre int main(). Any help would be awesome.
bool isSymmetric(vector<int> &vect, int Value)
{
for (int i = 0; i < Value; i++)
for (int j = 0; j < Value; j++)
if (vect[i][j] != vect[j][i])
return false;
return true;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > vec;
cout << "NxN matrix N: ";
int Value;
cin >> Value;
cout << Value << "x" << Value << " matrix\n";
for (int i = 0; i < Value; i++) {
vector<int> row;
for (int j = 0; j < Value; j++) {
cout << "Enter a number (0 or 1): ";
int User_num;
cin >> User_num;
while (User_num != 0 && User_num != 1) {
cout << "Invalid Entry! Enter 0 or 1!\n";
cout << "Enter a number (0 or 1): ";
cin >> User_num;
}
row.push_back(User_num);
}
vec.push_back(row);
}
cout << endl;
for (int i = 0; i < Value; i++) {
for (int j = 0; j < Value; j++) {
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
system("pause");
return 0;
}

Array search and unique value addition

(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}

C++ function and array homework

Create a function that prints the array to the screen as a table with the appropriate rows and columns. Use setw() to ensure the numbers have enough room. You may assume the numbers are no more than 3 digits each. Include the row and column labels.
In main, ask the user to supply a row and column and a value (no more than 3 digits), then put the value into the array at that row and column. Print the result and ask the user for another row, column and value. Repeat until the user is finished.
Once finished, compute and print the total of the values in the array.
#include <iostream>
#include <iomanip>
using namespace std;
const int ROWS= 4;
const int COLS = 3;
const int WIDTH = 4;
const char YES = 'y';
int total = 0;
void print(int arr[ROWS][COLS]);
int main()
{
int arr[ROWS][COLS];
char ans = YES;
int val;
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++)
arr[r][c] = 0;}
while (tolower(ans) == YES){
int row = -1;
int col = -1;
cout << "Row? ";
cin >> row;
cout << "Columns? ";
cin >> col;
while (row < 0 || row >=ROWS){
cout << "Only value under " << ROWS << " is accepted, try again: ";
cin >> row;
}
while (col < 0 || col >= COLS){
cout << "Only value under " << COLS << "is accepted, try again: ";
cin >> col;
}
cout << "Value? ";
cin >> val;
arr[row][col] = val;
print(arr);
cout << "Again (y/n)? ";
cin >> ans;
}
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++){
total += arr[r][c];
}
}
cout << "Sum of all values is " << total << endl;
// Print array with labels
// get input from user
// print array again - repeat until user wishes to quit
return 0;
}
void print (const int arr[ROWS][COLS])
{
cout << endl << endl;
for (int i = 0 ; i < COLS; i++)
cout << setw(WIDTH) << i;
cout << endl;
for (int r = 0; r < ROWS; r++)
cout << setw(WIDTH) << r << "|";
for (int r = 0; r < ROWS; r++)
for (int c = 0; c< COLS; c++)
cout << setw(WIDTH) << arr[r][c];
cout << endl << endl;
}
I dont know where I did wrong on this one but when I complie, I got the LD return 1 exit status error, Can you please help?
The definition and the declaration of your print function are different.
Change the declaration of your print() function.
void print(int arr[ROWS][COLS]);
to
void print(const int arr[ROWS][COLS]);