Click here to Skip to main content
16,004,587 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hi guys ,, soo i wanted to compare two arrays elements ,, and see the bigger value between each two elements

What I have tried:

C++
#include <iostream>
using namespace std;
int main()
{
int a[] =  {1, 2, 3, 4};
int b[] =  {0, 1, 5, 6};
for (int i=0;i<4;i++)
{
    for (int j=0;j<4;j++)
    {
        if (a[i] > b[j])
        {
            cout << a[i] << " | ";
        }
        else if (a[i] < b[j])
        {
            cout << b[j] << " | ";
            break;
        }
    }
}
    
    return 0;   
}


i wanted to get value like this
C++
1  | 2 | 5  | 6 |

insted i'm getting like this
C++
1 | 5 | 2 | 2 | 5 | 3 | 3 | 5 | 4 | 4 | 5 |
Posted
Updated 27-Mar-16 11:55am
Comments
Member 12173667 27-Mar-16 18:07pm    
thanks it worked :)

You're comparing each value in a[] to each value in b[] because you nested two for-loops. To get your expected result you only need a single for-loop and to compare the same indices of a[] and b[] with each other.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 27-Mar-16 21:21pm    
5ed.
—SA
Only advice for HomeWork:
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Run your code step by step, inspect variables, be very attentive to what your program is doing. You should find quickly what is wrong.
 
Share this answer
 

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