solutions

up

back

 

chapter 1 chapter 2 chapter 3

Home keywords c bibliography

 

solutions chapter 1

    Exercise 1

type number of bits minimum maximum
unsigned short 16 0 65535
signed short 16 -32768 32767
unsigned long 32 0 4294967295
signed long 32 -2147483648 2147483647

Note that if you do not modify the int type you get (on 32 bit systems) a signed long integer. Using "short int" for example gives you a signed short integer. If you use signed integers you loose one of the bits for the sign thus reducing the absolute maximum by a factor of 2. Also notice that in case of signed integers the negative absolute value is larger by one compared to the positive absolute value. This is an effect of the intrinsic representation of positive and negative numbers. Lets see two examples of 8 bit signed integers:

Bit 7 6 5 4 3 2 1 0
2n sign 64 32 16 8 4 2 1
  0 1 1 1        
  1 1 1 1 1 1 1 1

So we compare two numbers with all 7 bits set, just differing in the sign bit. The positive one is simply given by 2^7-1=127. The negative one instead is -1 and is given by -(2^7-(2^7-1)), where the first occurrence of 2^7 refers to the maximum range and the value in brackets (2^7-1) is the number you would get without the sign bit. That way, the absolute of the smallest number you can achieve is always by one larger than the highest positive one.

Of course you have to reduce the number of bits in the example program by one for the type signed short: you only have 15 valid bits for the number, the sixteenth is for the sign! This means a number with all 15 bits set is already the largest one you can get. A further increase by one will just invert the sign bit und you go from the positive numbers to the negative.

    Exercise 2

Well, this one was not too complicated, i hope. On the left column we find the value of our counting variable (here i) going from 1 to 20. The left column is the product i*(i-1). A possible program to achieve this looks so:

#include <iostream>

void main()
{
    int i;
    
    for (i=1;i<=20;i++) cout << i << "\t" << i*(i-1) << "\n";
}

email me: Daniel Schürmann