- 1
How to compare elements in an array?
Does anyone know how to compare elements in an array? For example If i have an array Array[5] {1,3,6,3,7}; Is there a way to see if we can compare each elements to another and see if they are equal? Thanks
6 Answers
+ 2
The same way how you would with any variable.
bool var = (Array[0] == Array[1]);
var will evaluate to false because 1 != 3.
+ 1
No, you don't need a boolean every comparison. That was just my example of evaluting whether a statement was true or false.
And what do you mean by comparing every element in the array?
+ 1
Bare with me, as I am not familiar with Poker at all. But is this something what you're looking for?
#include <iostream>
int arr[9] = { 1, 2, 3, 4, 5, 6, 7, 3, 9};
bool check()
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (i == j)
continue;
if (arr[i] == arr[j])
return true;
}
}
return false;
}
int main()
{
if (check())
{
std::cout << "Matching number";
}
else
{
std::cout << "No matching number";
}
}
In the array of 9 elements, we have 2 matching numbers at arr[2] and arr[7], therefore the function returns true, and "Matching number" is printed out from main.
Note that I have used arr[] as a global array in this example, you should probably find an alternative way.
+ 1
Wow, thx for the help, i didnt think of comparing 2 arrays.
0
So does that mean I have to type out each Boolean variable to compare each element?
Is there a loop or something to compare the every element with in the array?
0
I am trying to write a poker program and want to idenfity the array (the array represents the users hand) to see if any of the elements (the elements represent each cards) pairs up with each other.