Reputation: 41
I'm creating a program for myself to find and display duplicate elements from 2 separate arrays. CPP was a number of years ago so I'm a lot rusty getting back in to it. I've searched and read different boards but nothing is hitting the mark. Here is what I'm trying to make happen:
Take all the elements from 'a' and compare them to 'b'. If there is a duplicate number in 'b', then display that number(s).
I've tried using int and double but end up with the same results each time. It seems like the code is finding duplicates for each element even when some of the elements are 2 digits.
In the code below, the number that should show up is 64. Instead I get;
Duplicate found: -9.25596e+0611
Duplicate found: -9.25596e+0612
Duplicate found: -9.25596e+0613
Duplicate found: 44
... and so on. I know I'm missing something and probably not using the right combination of words to find what I'm looking for. Any pointers or links that may help would be most appreciated.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double dupi;
double dupj;
double a[5] = { 8, 22, 24, 38, 64 };
double b[5] = { 33, 47, 58, 59, 64 };
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
if (a[i] == b[j])
dupi = i;
dupj = j;
cout << "\nDuplicate found: " << dupi << dupj << endl;
}
}
cin.get();
return 0;
}
Duplicate found: 64
Upvotes: 0
Views: 47
Reputation: 4395
you need to put braces around if condition.
otherwise it is going to print uninitialized value of dupi
As you need duplicate value, not the index so you
should use dupi =a[i];
instead of dupi = i;
should use dupi =a[j];
instead of dupi = j;
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
if (a[i] == b[j]){ //use braces so that code will hit only when condition is true
dupi = i; //should be a[i] or b[i]
dupj = j; //should be a[i] or b[i]
cout << "\nDuplicate found: " << dupi << dupj << endl;
} //closing braces
}
}
Upvotes: 0
Reputation: 52471
dupi = i;
is performed only when (a[i] == b[j])
is true; but dupj = j;
and cout << "\nDuplicate found: "...
are performed unconditionally. You likely meant to add a pair of braces. As written, you are printing the value of uninitialized variable.
Upvotes: 1