Answer the question
In order to leave comments, you need to log in
How to write the same values from two arrays to the third one?
task:
there are two arrays, write the same values to the third
one, it seems to be written to me, but "garbage values" appear,
here is my code
#include <iostream>
#include <time.h>
using namespace std;
void main()
{
const int size = 10;
int massA[size], massB[size],massC[size];
srand(time(NULL));
for (int i = 0; i < size; i++)
{
massA[i] = rand() % 10;
cout << massA[i] << " ";
}
cout << endl;
for (int i = 0; i < size; i++)
{
massB[i] = rand() % 10;
cout << massB[i] << " ";
}
cout << endl << "spil'ni elementy:" << endl;
for (int j=0, i = 0, z=0; i < size,j<size,z<size; i++,j++,z++)
{
if (massA[i] == massB[j]) {
massC[z] = massA[i];
cout << massC[z] << " ";
}
}
cout << endl;
system("pause");
}
Answer the question
In order to leave comments, you need to log in
Take a closer look at this code:
for (int j=0, i = 0, z=0; i < size,j<size,z<size; i++,j++,z++)
{
if (massA[i] == massB[j]) {
massC[z] = massA[i];
cout << massC[z] << " ";
}
}
for (int i = 0; i < size; ++i)
{
if (massA[i] == massB[i]) {
massC[i] = massA[i];
cout << massC[i] << " ";
}
}
int k = 0;
for (int j = 0; i < size; ++i)
{
for (int j = 0; j < size; ++i)
{
if (A[i] == B[j])
{
// Здесь можно сделать так:
C[k] = A[i];
++k;
// или одной строчкой
// C[k++] = A[i]
}
}
}
system("pause");
function , which pauses your program and starts the one given in the argument. People who don't use Windows won't be able to run your code because they don't have the pause program .
1. Are the same values equal in value and position? in the specified implementation it seems that it is, but we know that...
2. massC[z] == massA[i]; this is a comparison operation with an unused result - assignment 3 is more appropriate
. To compare and find the same elements, a nested loop is required, most likely, friendly
1. In your version, only values that are in the same positions are compared and written to the same position in the 3rd array. This is to the question whether it is necessary to look for identical only in value or identical in value and position.
2. Since the array is essentially a pointer to a number of memory cells, without its initialization, when accessing any element, the value stored in this cell will be returned. And in the absence of initialization, there are no guarantees that there will be no garbage data in this cell, which happens almost 100%.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question