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 return true when the value of the integer argument is negative, false otherwise.
  • Then write a main function (as seen in the lecture and on the previous page). Call the isNegative function with some test values and display the return values using the printf function. Don't forget the #include statements for stdio.h and stdlib.h. The main function should always return EXIT_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 isNegative function, 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 bool as a return type. Recall, bool is not a keyword of the C language. Instead this type is defined in the library.
  • Rewrite the isNegative function 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 as if statements 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.