I am trying to compare two arrays.where if it is true it needs to print the string.since it need to print only one time but the string is printing three times .where i have stored three values in both arrays.can you guys spot and tell me what is wrong.
for (int i = 0; i < n; i++)
{
if (l[i] == g[i])
{
cout << "equal" << endl;
}
else if (l[i] < g[i])
{
cout << "lesser" << endl;
}
else if (l[i] > g[i])
{
cout << "greater" << endl;
}
}
I'm guessing that you're trying to do a lexicographic comparison .
It should be obvious that if you want to print the message only once then you shouldn't put the print statements inside the loop.
The following code works how I think you want your code to work. The result of the comparison is stored in a variable result
and that variable is examined only after the loop has finished. I use break because once you have found an item that is not equal there is no need to carry on the comparison.
int result = 0;
for (int i = 0; i < n; i++)
{
if (l[i] < g[i])
{
result = -1;
break;
}
else if (l[i] > g[i])
{
result = +1;
break;
}
}
if (result == 0)
cout << "equal" << endl;
else if (result < 0)
cout << "lesser" << endl;
else
cout << "greater" << endl;
You could simplify:
for (int i = 0; i < n; ++i)
{
const int l_value = l[i];
const int g_value = g[i];
if (l_value == g_value)
{
cout << "slot[" << i << "] is equal\n";
}
else
{
if (l_value < g_value)
{
cout << "slot[" << i << "] is less than\n";
}
else
{
cout << "slot[" << i << "] is greater than\n";
}
}
}
In order compare the entire array, you'll need to sort it first. The "less than" and "greater than" apply to a sorted array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.