0

Before I start I must notice that I am a begginer in C++. I have a code (see below), In this code I have two arrays with 10 random numbers but In tab_A numbers are the same like in tab_B - I don't know how to solve this. Also I don't know how to merge/add/sum these two arrays in new array tab_C and print result.

#include <iostream>
#include <cstdio>
#include <time.h>
#include <cstdlib>

using namespace std;

int gen() {
  return rand() % 11;
}
int main()
{
    
    int tab_A[10];
    cout<<"TABLICA A DEBUG"<<endl;
    srand (time(NULL));
    for (int i=0; i<10; i++)
    {
        tab_A[i] = gen();
        cout<<tab_A[i]<<endl;
    }
    
    int tab_B[10];
    cout<<"TABLICA B DEBUG"<<endl;
    srand (time(NULL));
    for (int i=0; i<10; i++)
    {
        tab_B[i] = gen();
        cout<<tab_B[i]<<endl;
    }
    
    int tab_C[10];
    cout<<"TABLICA C DEBUG"<<endl;
    
    int sumAB=0;
    sumAB=tab_A[10]+tab_B[10];
    
    tab_C[10]=sumAB;
    cout<<tab_C[10]<<endl;
    return 0;
}
1
  • Can you share an example as to how you want to add the two arrays? Commented Dec 7, 2020 at 19:09

1 Answer 1

2

In the code, you have called srand twice with the same seed. Hence, the numbers that will be randomly generated will be the same. If you want to generate random numbers it is advisable to set seed only once.

Also, there seems to be an issue in the code. C++ has 0-indexing. Hence, the lines

sumAB=tab_A[10]+tab_B[10];
tab_C[10]=sumAB;
cout<<tab_C[10]<<endl;

will give errors.

As the size of tab_C is 10 so the index of the last element would be 9.

Sign up to request clarification or add additional context in comments.

3 Comments

Okay srand solvet. Now I have problem with tab_C. As output I have "1". I changed that array size to 11
Do you want to add element by element?
I want to perform the addition int sumAB=0; sumAB=tab_A[10]+tab_B[10]; for(int i=0; i<tab_C[10]; i++) { for(int i=0; i<tab_C[10]; i++) { tab_C[i]=sumAB; } } this is my last code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.