Given five integers as input, display each in the order entered by the user with the character '>', '<', or '=' in between each pair of numbers that accurately represents their relationship.
How do i get the greater than, less than, equal to signs to switch? I am not allowed to use logical operators, relational operators, or selection constructs.
Here is what the program should look like:
Example Execution #1:
Enter the five integer values: 4 8 9 0 3
4 < 8 < 9 > 0 < 3
Example Execution #2:
Enter the five integer values: 2 2 3 3 2
2 = 2 < 3 = 3 > 2
#include <iostream>
int main()
{
constint n = 5 ;
int numbers[n] ;
// read in n numbers
for( int i = 0 ; i < n ; ++i ) std::cout << "? " && std::cin >> numbers[i] ;
std::cout << '\n' << numbers[0] ; // print the first number
// create an array of symbols: symbols[0] == '>' symbols[1] == '=' symbols[2] == '<'
constchar symbol[] = { '>', '=', '<' };
// for the next n-1 numbers
for( int i = 1 ; i < n ; ++i )
{
constint previous_number = numbers[i-1] ;
constint this_number = numbers[i] ;
// not allowed to use logical operators, relational operators, or selection constructs.
// compute the difference between this number and the previous number
int diff = this_number - previous_number ;
// diff is negative if previous_number > this_number,
// zero if previous_number == this_number,
// positive if previous_number > this_number
// if diff is zero, leave it unchanged
// if diff is non-zero, make it an odd number
diff += bool(diff) + (diff%2) ;
// note: bool(diff) + (diff%2) == 0+0 == 0 if diff is zero
// note: bool(diff) + (diff%2) == 1-1 == 0 if diff is an odd negative number
// note: bool(diff) + (diff%2) == 1+1 == 2 if diff is an odd positive number
// note: bool(diff) + (diff%2) == 1-0 == 1 if diff is an even negative number
// note: bool(diff) + (diff%2) == 1+0 == 1 if diff is an even positive number
constint index = (diff%2) + 1 ; // index == zero if diff is negative,
// index == 1 if diff is zero,
// index == 2 if diff is positive
// print the appropriate symbol followed by this number
std::cout << ' ' << symbol[index] << ' ' << this_number ;
}
std::cout << '\n' ; // finally print a newline
}
This can be done in just a few instructions on most CPUs because (x<0) can be computed by shifting the sign bit down to bit 0. To compute x>0 you just do (-x) < 0.