I need some assistance with creating a function - c++

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];
}
}

Related

Finding min and max in 2-D arrays?

After running this code , it will generate a random array of desired rows and columns . Then a loop will divide the array by its diagonal into an upper side and lower side.In the upper side the loop will look for a max number and in the lower side the loop will look for a min number . Then in the final stage I need to change the positions of min and max . Max in place of min and vice versa.The code runs and finds the min and max.Don't know how to change their places.
Code
#include <iostream>
#include <time.h>
#include <limits.h>
using namespace std;
int main(){
int rows, columns;
int max = INT_MAX;
int min = INT_MIN;
int XindexOfMax, YindexOfMax;
int XindexOfMin, YindexOfMin;
cout << "Enter rows: ";
cin >> rows;
cout << "Enter columns: ";
cin >> columns;
int **array = new int *[rows]; //generating random array
for(int i = 0; i < rows; i++)
array[i] = new int[columns];
srand((unsigned int)time(NULL)); //generating randoms
for(int i = 0; i < rows; i++){ //loop for the main array
for(int j = 0; j < columns; j++){
array[i][j] = rand() % 10;
cout << array[i][j] << " ";
}
cout << "\n";
}
cout << "For finding Max: " << endl;
for(int i = 0; i < rows; i++){ //upper half of the diagonal
for(int j = 0; j < columns - i; j++){
cout << array[i][j] << " ";
if(array[i][j] > max){
max = array[i][j];
XindexOfMax = i; //find x and y coordinates if max
YindexOfMax = j;
}
}
cout << "\n";
}
cout << "For finding Min: " << endl;
for (int i = 0; i < rows; i++){ // lower half of the diagonal
for (int j = 0; j < columns; j++){
if (j < columns - i - 1){
cout << " ";
}
else{
cout << array[i][j] << " ";
if(array[i][j] < min){
min = array[i][j];
XindexOfMin = i; //find x and y coordinates if min
YindexOfMin = j;
}
}
}
cout << "\n";
}
cout << "Result" << endl;
//swapping positions of min and max
std::swap(array[XindexOfMax][YindexOfMax], array[XindexOfMin][YindexOfMin]);
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
cout << array[i][j] << " "; //Printing the final array
}
cout << "\n";
}
return 0;
}
In addition to the min and max values, you need to remember the indizes where you found min and max, respectively. Then you can exchange the values (either manually or by using std::swap).
BTW: you need to initialize max and min with INT_MIN and INT_MAX, respectively, and not the other way around.
So it needs to be
int max = INT_MIN;
int min = INT_MAX;
Otherwise, if you write int max = INT_MAX, then no comparison like if(array[i][j] > max) will ever evaluate to true, since there is no integral value greater than INT_MAX.
The swapping is done at the end of main() using std::swap().
I broke a couple of routines into functions. The answer would be improved by breaking out more functions so that each function performs a single task. Still, I added a class, yet tried to stay true to your original design for printing the triangle halves. Hope you can handle some classes at this point.
#include <iostream>
#include <time.h>
#include <limits.h>
#include <cmath>
using namespace std;
class Point {
public:
Point(int x, int y, int value) : x(x), y(y), value(value) {}
int X() { return x; }
int Y() { return y; }
int Value() { return value; }
void SetValue(int valueArg) { value = valueArg; }
void SetPoint(int xArg, int yArg, int valueArg) {
x = xArg;
y = yArg;
value = valueArg;
}
string to_string() {
return std::to_string(value);
}
private:
int x;
int y;
int value;
};
void PrintArray(int **array, int rows, int columns) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << array[i][j] << " ";
}
cout << "\n";
}
}
int main() {
int rows, columns;
cout << "Enter rows: ";
cin >> rows;
cout << "Enter columns: ";
cin >> columns;
int **array = new int *[rows]; //generating random array
for (int i = 0; i < rows; i++)
array[i] = new int[columns];
srand((unsigned int) time(NULL));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = rand() % 10; //generating randoms
}
}
PrintArray(array, rows, columns);
Point maxPoint = Point(0, 0, INT_MIN); // initialize max
Point minPoint = Point(0, 0, INT_MAX);;
cout << "For finding Max: " << endl;
for (int i = 0; i < rows; i++) { //separating the upper half
for (int j = 0; j < columns - i; j++) {
if (j > columns - i) {
cout << array[i][j] << " ";
} else {
cout << array[i][j] << " ";
if (array[i][j] > maxPoint.Value()) {
maxPoint.SetPoint(i, j, array[i][j]);
}
}
}
cout << "\n";
}
cout << "For finding Min: " << endl;
for (int i = 0; i < rows; i++) { //separating the lower half
for (int j = 0; j < columns; j++) {
if (j < columns - i - 1) {
cout << " ";
} else {
cout << array[i][j] << " ";
if (array[i][j] < minPoint.Value()) {
minPoint.SetPoint(i, j, array[i][j]);
}
}
}
cout << "\n";
}
cout << "array before: " << endl;
PrintArray(array, rows, columns);
cout << "Swapping " << "maxPoint(" << maxPoint.X() << ", " <<
maxPoint.Y() << ") with minPoint("
<< minPoint.X() << ", " << minPoint.Y() << ")" << endl;
std::swap(
minPoint.GetCellReference(array),
maxPoint.GetCellReference(array));
PrintArray(array, rows, columns);
return 0;
}
As mentioned in one of the comments, std::swap() is one method of performing a swap. I have modified the example to use std:swap() at the end of main();

The difference between 2 arrays in c++ A\B

So I have 2 arrays. Let's say the first one it's called a and the second one b. The first one uses "i" for it's elements and the second one uses "j".
For example we have a[ 1 2 3 4] and b[3 4 5] it should show c[1 2]. In the array c I want to show the elements that are in a and aren't in b.
This is what I've tried, but without succes:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
If the items are sorted, use std::set_difference:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 3, 4, 5 };
std::vector<int> cv;
std::set_difference(std::begin(a), std::end(a),
std::begin(b), std::end(b),
std::back_inserter(cv));
for (auto& s : cv)
std::cout << s << "\n";
}
Output:
1
2
The advantage of using the STL algorithms is that the purpose of the code is known immediately just by looking at the name of the function, and that they work every time (if you give them the correct parameters). Note the lack of comments -- any competent C++ programmer understands right away what's being done.
On the other hand, if you didn't mention what your original code was trying to do (including removing the comments), it would take much more effort to figure out what it's supposed to be doing, and as you've seen, it contains bugs.
Your logic is wrong.
Explanation
So the thing that we will do
For each element in a we will have to check if it is there in array b or not.
If we see any element of a[i] in b[1..m] then we can't add it to c.
So in code we just mark it by f=1
When I get out of that second for loop I want to check if that a[i] is eqaul to any of the element in b[1..m] in which case f will be 1. But if it is 0 then add it to array c[].
Correct one
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
Where OP went wrong?
Being not equal to one element of b[] doesn't guarantee that the element is not appearing b[0..m-1] . This is where op went wrong.
In the for loop
for(j=0;j<m;j++) you are checking if particular a[i] is equal to b[j] or not. If that is the case then it is added to c[] . It is wrong. Also i is not incremented in the loop unless j==m and as in the for loop the condition is j<m so i is never incremented. And k is incremented every time so not every element in c is valid they may contain garbage value even after processing.
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j]) // this doesn't mean that it is not appearing in `b`
c[k] = a[i];
k++; // k is incremented in every iteration which is wrong. It should be only when we are sure that `a[i]` is not in `b[0..m-1] `
while (j == m && i < n)
i++; // OP is not using it anywhere...this is redundant.
}
what op did?
Compared first element of a[0] with every element of b[0..m-1] and array c[] contains m elements irrespective of what a[] and b[] is, out of which
c[i]={ a[0] if b[j]==a[0]
{ garbage value if b[j] not equal to a[0]
Dry Run of OP's code
k = 0; i = 0;
for (j = 0; j < m; j++) {
if (a[i] != b[j])
c[k] = a[i];
k++;
while (j == m && i < n)
i++;
}
Input
Case: 1 2 3 4 :a[]
2 3 4 1 :b[]
Step 1: i=0 a[0]!=b[0] is true so c[0]=a[0]. the `while loop` not entered.
j++
Step-2: i is still 0. a[0]!=b[1] so it is added c[1]=a[0]. While loop not entered.
j++
Step-3: i is still 0. a[0]!=b[2]. So c[2]=a[0]. While loop skipped.
j++
Step-4: i is still 0. a[0]==b[3] is true so no assignment done. But k is incremented. so c[3]=garbage. j=3 so while loop skipped
j++
Out of for loop.
Output: [here x is garbage value]
a[]: 1 2 3 4
b[]: 2 3 4 1
c[]: 1 2 3 x
Example test case
1 2 3 4 :=a
2 3 4 1 :=b
Corrected Code
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[50], b[50], c[50], i, j, k, n, m;
cout << "n= "; cin >> n;
//Read arrays
for (i = 0; i < n; i++) {
cout << "a[" << i << "]: "; cin >> a[i];
}
cout << "\nm= "; cin >> m;
for (j = 0; j < m; j++) {
cout << "b[" << j << "]: "; cin >> b[j];
}
//Show the arrays
cout << endl;
cout << "\na[ ";
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "]";
cout << endl;
cout << "\nb[ ";
for (j = 0; j < m; j++) {
cout << b[j] << " ";
}
cout << "]";
//Calculate the difference
k = 0; i = 0;
int k=0;
for(int i=0;i<n;i++)
{
int f=0;
for(int j=0;j<m;j++)
{
if(a[i]==b[j])
f=1;
if(!f)
c[k++]=a[i];
}
}
//Show the difference array
cout << endl;
cout << "\nc[ ";
for (i = 0; i < k; i++) {
cout << c[i] << " ";
}
cout << "]";
return 0;
}
Your code seems to check if the elements in a are equal to all elements of b. If you just want to check the elements in a if they are equal to at least one element of b, you can do
for (int i=0; i<n; i++) {
bool found = false;
for (int j=0; j<m; j++) {
if (a[i] == b[j]) {
found = true;
break;
}
}
if (!found) {
std::cout << "a["<<i<<"] is not in b"<<std::endl;
}
}
Or add the element to c, but I would recommend to use std::vector<int> c for that.
In the array c I want to show the elements that are in a and aren't in b
It seems like you are looking for std::set_difference
int a[4] = {1, 2, 3, 4}, b[3] = {3, 4, 5};
int c[2] = {}; // declare c with enough space to hold all the elements in result
std::set_difference(a, a + 4, b, b + 3, c); // now c contains the element that are in a but not in b
You can do this very easily using 'set'.
#include<iostream>
#include<set>
int main(){
std::set<int> a = {1,2,3,4} , b = {3,4,5};
for(int const inB : b)
a.erase(inB);
for(int const inA : a)
std::cout << inA << " ";
std::cout << std::endl;
return 0;
}

Program that receives 2 arrays and checks how many times 1 is included in the other

I need to write a program that receives 2 arrays and checks how many times 1 is included in the other...
But I cant find what is wrong with my program! tx!!
#include <iostream>
using namespace std;
int main()
{
int vector1[500];
int vector2[100];
int a = 0, b = 0, count = 0, k = 0;
cout << "enter size of first array:" << endl;
cin >> a;
cout << " enter first array values:" << endl;
for (int i = 0; i < a; i++)
cin >> vector1[i];
cout << "enter size of second array:" << endl;
cin >> b;
cout << "enter secound array values:" << endl;
for (int i = 0; i < b; i++)
cin >> vector2[i];
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i + k] == vector1[j])
{
count++;
k++;
}
else
k = 0;
cout << count << endl;
system("pause");
return 0;
}
Why at all do you need k? The problem is about all inclusions of all elements right? If O(n^2) complexity is fine, then...
for (int i = 0; i < b; i++)
for (int j = 0; j < a; j++)
if (vector2[i] == vector1[j])
count++;
One obvious disadvantage of the code above is that you'll get the total sum of all occurences of elements from vector1 in vector2. The key idea remains the same in case you need to know, which elements exactly appeared in another array and how many times, you'll just have to use map or other vector.

Passing 2D array to a Function in 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;
}

send dynamic array of pointer to function in c++

I trying to send array to function, but my program gets stuck
int main()
{
int n, i;
bool random;
cout << "number of elements in array:"; cin >> n;
cout << "use random values?"; cin >> random;
int* arr = new int[n]; //create int array with n size
init_array(random, n, arr); //fill array using function
for (i = 0; i <= n; i++) //display array
cout << " " << arr[i];
return 0;
}
This function should fill array with random number or input from keyboard
void init_array(bool random, int n, int* arr)
{
int i;
if (random)
{
srand(time(0)); //initialize random;
for (i = 0; i < n; i++)
arr[i] = rand() % 100;
}
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
}
Is there any way send dynamic array to function?
When you do not use brackets after your for-loop, only the first statement is used as a loop:
else
for (i = 0; i<n; i++)
cout << "arr[" << i << "]: "; cin >> arr[i];
This loop will attempt to print "arr[#]" n times, and then ask for an input (which will attempt to be placed in the item 1 after the last element in your array (UB).
What you want is this:
else
{
for (i = 0; i<n; i++)
{
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
}
You also have a problem with your output:
for (i = 0; i < n; i++) // <= would attempt to print 1 more item than exists in the array
And just for completeness, most of these issues go away when you use a container that does all of this for you:
int main()
{
int n = 0;
bool useRandom = false;
std::cout << "number of elements in array:";
std::cin >> n;
std::cout << "use random values?";
std::cin >> useRandom;
std::vector<int> arr(n);
init_array(useRandom, arr);
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
void init_array(bool useRandom, std::vector<int>& vec)
{
::srand(time(0)); //initialize random;
int n = 0;
std::transform(vec.begin(), vec.end(), vec.begin(), [&](int i)
{
if (useRandom)
{
i = rand() % 100;
}
else
{
std::cout << "arr[" << n++ << "]: ";
std::cin >> i;
}
return i;
});
}
Your code is asking for a number at the end because of last cin>>n
fix else part in init_array as:
else
for (i = 0; i<n; i++)
{ //Notice braces
cout << "arr[" << i << "]: ";
cin >> arr[i];
}
Also fix:
for (i = 0; i < n; i++) //display array from index 0 to n-1
cout << " " << arr[i];