Click here to Skip to main content
15,895,667 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I would like to create some sort of function that checks all the values of an array and, if they are all the same, sets a bool to false, and if one of the values is different then the rest, sets the bool to true.

Example:
Say the array1 contains {0, 0, 0} and array2 contains {0, 1, 0}
int Array[3];
bool TheBool(false);

for(int i = 0; i < SizeOfArray; i++)
{
  if(all elements of the array are the same)
  {
    TheBool = false;
  }
  else
  {
    TheBool = true;
  } 
}


With array1, TheBool should be false, and with array2, it should be true.

Thanks in advance to anyone who can help me out with this :)
Posted
Comments
Pablo Aliskevicius 26-Mar-12 11:13am    
This looks like a homework question. If so, please say so.
LucasShadow 26-Mar-12 15:20pm    
No its not a homework question. Its something I am just trying to figure out myself as I continue to self-teach myself c++
enhzflep 26-Mar-12 11:26am    
So why not do it the same way you'd do it on a piece of paper with a list of numbers?

That is to say,

For all elements except first one:
if (currentElement != previousElement) allSame = false

1 solution

A naive implementation could be something like this;

C++
#include <iostream>

using namespace std;

bool checkArray(int a[], size_t length)
{
	if (length < 2)
		return true;
	else
	{
		int value = a[0];
		for(int i = 1; i < length; ++i)
		{
			if (a[i] != value)
				return false;
		}

		return true;
	}
}

int main()
{
	int myArray[3];
	myArray[0] = 1;
	myArray[1] = 2;
	myArray[2] = 1;

	cout << (checkArray(myArray, 3) ? "All are same" : "There are different numbers in there!") << endl;
	return 0;
}


Hope this helps,
Fredrik
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900