Reputation: 29
So my task is to make 3 arrays. User has to put integers in 2 of the arrays, then I must compare the integers in each position and put the higher integer in a third array, that has to be displayed on the screen.
Here is my program:
int main() {
int n; // number of elements
cin >> n;
int* array = new int[n];
int* array2 = new int[n];
int* array3 = new int[n];
cout << "First array: " << "\n";
for (int i = 0; i < n; i++) {
cin >> array[i];
}
cout << "Second array:" << "\n";
for (int i = 0; i < n; i++) {
cin >> array2[i];
}
for (int i = 0; i < n; i++) {
if (array[i] > array2[i]) {
array[i] = array3[i];
continue;
} else if (array[i] <= array2[i]) {
array2[i] = array3[i];
continue;
}
}
for (int i = 0; i < n; i++) {
cout << array3[i] << "\n ";
}
delete[] array;
delete[] array2;
delete[] array3;
}
So, if my first array is 1 2 3 4
and second array is 5 6 7 8
- it displays some massive negative numbers as output (-842150421
).
Where is my mistake?
Upvotes: 0
Views: 85
Reputation: 449
int maxima(int i , int j)
{
if(j > i)
return j;
return i;
}
int main()
{
int n; //number of elements
cin >> n;
int* array = new int[n];
int* array2 = new int[n];
int* array3 = new int[n];
cout << "First array: " << "\n";
for (int i = 0; i < n; i++)
cin >> array[i];
cout << "Second array:" << "\n";
for (int i = 0; i < n; i++)
cin >> array2[i];
for(int i = 0; i < n; i++)
array3[i] = maxima(array[i], array2[i]);
delete[] array;
delete[] array2;
delete[] array3;
return 0;
}
I hope this helps
Upvotes: 0
Reputation: 1143
You are showing your array3
but you haven't added any data to it, you must assign data to your array3 I suppuose that after the comparation you do between array and array2 you get the bigger data into the array3.
int main(){
int n; //number of elements
cin >> n;
int* array = new int[n];
int* array2 = new int[n];
int* array3 = new int[n];
cout << "First array: " << "\n";
for (int i = 0; i < n; i++)
cin >> array[i];
cout << "Second array:" << "\n";
for (int i = 0; i < n; i++)
cin >> array2[i];
for (int i = 0; i < n; i++) {
if (array[i] > array2[i]) {
array3[i] = array[i];
continue;
}
else if (array[i] <= array2[i]) {
array3[i] = array2[i];
continue;
}
}
for (int i = 0; i < n; i++)
cout << array3[i] << "\n ";
delete[] array;
delete[] array2;
delete[] array3;
}
I haven't modified your code but:
continue;
as you have an else clause the code will not enter in the other condition.I would remove the second comparation because if it's not bigger there is the case that is equal or less so you could leave just the else without any if.
if (array[i] > array2[i]) { array3[i] = array[i]; } else{ array3[i] = array2[i]; }
Upvotes: 1