Hi everybody,

I have just started working with C++ and I find it intersting and facinating!! However, I am struggling a bit with a problem. I want to find out if the elements in an integer array are increasing or not. I have used a nested loop, but I think the problem is that it compares only one and one element with each other. If my array consist of the numbers { 1, 3, 4 }, it is indeed increasing, but the same thing is true for the array { 1, 3, 2 }.

I attach the loop part of the program. Will appreciate any possible help on this!

Thanks
Gro

Attachments
for (int pass = 0; pass < arraysize - 1; pass++)

		for (int loop = 0; loop < arraysize - 1; loop++)
			
			if ( a[ loop ] < a [ loop + 1] )
				increasing = 1; 
	
	if (increasing == 1) 
			cout << "The array is increasing.";

	else
			cout << "The array is not increasing. ";

Here's my 30 second solution:

boolean compareArrays(int* array[])
{
      int start = array[0];
      for (int i=1; i<arraylength; i++)
      {
	 if (array[i] > start)
         {
              start = array[i];
         }
         else
         {
             return false;
         }
      }
      return true;
}

I haven't tested it, so I don't even know if it works or not.

for (int pass = 0; pass < arraysize - 1; pass++)

		for (int loop = 0; loop < arraysize - 1; loop++)
			
			if ( a[ loop ] < a [ loop + 1] )
				increasing = 1; 
	
	if (increasing == 1) 
			cout << "The array is increasing.";

	else
			cout << "The array is not increasing. ";

How does using a nested for loop change anything? What is the purpose of the outer loop; it just runs the innerloop (arraysize - 1) times without changing anything.

Your code sets 'increasing' to 1 if any pair of elements is increasing. This means that for increasing to be still not equal to 1 (assuming you initialized it with some value beforehand), every pair of elements would have to be in non-increasing order. This means that if increasing is not 1, then your array is in descending order (or at least non-increasing order, where some successive elements can be equal).

This article has been dead for over six months. Start a new discussion instead.