0

I am new, not that good with functions, and I am trying to solve this question:

  1. 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.

This is the picture that came with it

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

Jacked
  • 3
  • 7
  • 1
    Is array C meant to be 2 dimensional? – Tom May 21 '19 at 15:15
  • @Tom yes it is supposed to be 2d – Jacked May 21 '19 at 15:16
  • 1
    You must try something simpler first, like constructing a 2D array and filling it with `7`. – Beta May 21 '19 at 15:17
  • It's not clear from the wording of the question how array C is meant to be constructed from A and B. – Tom May 21 '19 at 15:17
  • @Tom i updated the photo since it was uncleaer – Jacked May 21 '19 at 15:18
  • 2
    `int A[100], B[100], C[200]` If C is 2D, then it must have 100^2 elements. Any reason for using c arrays instead of `std::array`? – Quimby May 21 '19 at 15:31
  • @Das_Geek how to approve your edit or is it approved – Jacked May 21 '19 at 15:32
  • A couple of quick things to make your life easier (since you're new). 1: Declare your variables as late as possible. For instance, instead of `int i; for(i = 0; etc.)`, you want `for(int i = 0; etc.)`. – hegel5000 May 21 '19 at 15:32
  • 2: With the exception of very traditional variable names such as `i` and `j`, a variable name should be one or more words in a written language explaining what the variable means (unless the variable's type is sufficiently descriptive). – hegel5000 May 21 '19 at 15:33
  • @Quimby what is std::array is there any differnce i used use namespace std does that has anything to do with this – Jacked May 21 '19 at 15:34
  • 1
    @Zack `[std::array](https://en.cppreference.com/w/cpp/container/array)`. It can be passed to functions while retaining it's size. So you wouldn't have to pass `N`... `using` only lets you reffer to `std::array` as `array`. But in your case you can also use `std::vector` as it's size can be set at run-time. – Quimby May 21 '19 at 16:35

3 Answers3

1

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.

Nordii
  • 479
  • 1
  • 5
  • 15
  • is there a way to do it with while – Jacked May 21 '19 at 16:15
  • can you have a look at my code i updated it and it is giving me a weird output i will upload the photo of output – Jacked May 21 '19 at 16:49
  • Just noticed a problem. In `Mix()`, `C[][]` is just a copy of the `C` that was passed in. Change the signature of the function to `void Mix(int (&A)[], int (&B)[], int (&C)[][200], int N, int M)` to keep from copying. This will also change `C` in the main function. See if that fixes your issue. – Nordii May 21 '19 at 17:13
  • no it keeps telling me a reference of type "int (&)[]" (not const-qualified) cannot be initialized with a value of type "int [100]" If_nested i updated the code once more – Jacked May 21 '19 at 17:25
  • To me it seems the source of the problem is changing `C` in the function and then using it in the main. To test the values in different places, I would try printing all of `C` inside `Mix()` or returning the matrix as pointers (`int** Mix(…)`) from the function and using the result in the print. – Nordii May 21 '19 at 17:41
  • can i use anything that is not pointers structures vectors classes or algorithms i am only two weeks into this and did not learn them yet – Jacked May 21 '19 at 17:43
  • try putting your printing loops in the `Mix()` function and see if the calculations are right. If they are right, then somewhere between the function running and returning, the value for `C` is not what you want. If that is the case, you cannot return an array as itself, but arrays are just pointers with a different syntax. If you store the returned `int**` in a variable of the same type (ex. `int** p = Mix(...)`), you should be able to treat `p` just like two arrays again. – Nordii May 21 '19 at 17:59
0

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;
}
  • thanks i was writing it as quick as possible that why i write = and [] instead of == and [] else i would have have problems only with the function.thanks and can i know how long you have been coding – Jacked May 21 '19 at 15:39
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:

  1. 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;
    }
}
  1. 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];
    }
}
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • is the any other way than vectors because i did not yet learn them – Jacked May 21 '19 at 17:35
  • @Zack I've edited with a couple workarounds, but fundamentally: No. `vector`s are what the language has given us to accomplish what you're trying to do. To try to do this without containers is really just trying to fight the language rather than to work with it. – Jonathan Mee May 21 '19 at 18:01
  • @Zack Understood. I'd try to use one of the alternatives I've provided where possible. I'll leave the `vector` approach as my primary answer however, as it is the best option to for readers who have not imposed your limitations. – Jonathan Mee May 21 '19 at 18:59
  • thanks for helping me out and i agree with your reply – Jacked May 22 '19 at 05:17