Manipulating Integers
The Sign of Integers
You should now write your first C program on your own:
- Create a new empty file
integers.c. - Write a function
isNegative, which takes a signed integer (int) as an argument and returns a boolean value. The function should returntruewhen the value of the integer argument is negative,falseotherwise. - Then write a
mainfunction (as seen in the lecture and on the previous page). Call theisNegativefunction with some test values and display the return values using theprintffunction. Don't forget the#includestatements forstdio.handstdlib.h. Themainfunction should always returnEXIT_SUCCESS. - Compile the code, using the usual compiler arguments, fix any compiler errors.
- Run the program and make sure that the output, i.e., the return values of the calls to the
isNegativefunction, is correct.
The Sign of Integers using Arithmetic
You know that the lab machines use the two's complement representation with 32 bits for signed integer numbers of type int. This means that the sign is explicitly encoded in the number representation.
- Make sure to use the type
boolas a return type. Recall,boolis not a keyword of the C language. Instead this type is defined in the library. - Rewrite the
isNegativefunction so that it only contains a single return statement and only contains arithmetic operations. - Consequently, your code should not use any comparison operators (
<,<=, ...) or use any conditional constructs, such asifstatements or the conditional operator (? :). - Compile the code as usual, fix any compiler errors.
- Make sure that the output produced by your program did not change.