# Exercises 1

(Sample solutions are online)

`pascal`has a function called`odd`, that given an integer returns 1 if the number is odd, 0 otherwise. Write an`odd`function for C and write a`main`routine to test it. (hint - You can use the fact that in C, if`i`is an integer then`(i/2)*2`equals`i`only if`i`is even).- Write a routine called
`binary`that when supplied with a decimal number, prints out that number in binary, so`binary(10)`would print out`1010`void binary(unsigned int number){ /* print decimal `number' in binary */ ... }

Then write a`main`routine to test it. Don't worry about leading zeroes too much at the moment. Note that`binary`returns a`void`, i.e. nothing. - Write a routine called
`base`that when supplied with a decimal number and a base, prints out that number to the required base, so`base(10,3)`would print out`101`void base(unsigned int number, unsigned int base){ /* print decimal `number' to the given `base' */ ... }

Then write a`main`routine to test it. - Print a table of all the primes less than 1000. Use any method you want.
The sieve method is described here:-
aim to create an array `
`number`' such that if`numbers[i] == PRIME`then`i`is a prime number. First mark them all as being prime. Then repeatedly pick the smallest prime you haven't dealt with and mark all its multiples as being non prime. Print out the primes at the end. Here's a skeleton:-#include <stdio.h> #include <stdlib.h> #define PRIME 1 /* Create aliases for 0 and 1 */ #define NONPRIME 0 int numbers[1000]; void mark_multiples(int num){ /* TODO: Set all elements which represent multiples of num to NONPRIME. */ } int get_next_prime(int num){ /* find the next prime number after `num' */ int answer; answer = num+1; while (numbers[answer] == NONPRIME){ answer= answer +1; if (answer == 1000) break; } return answer; } int main(){ int i; int next_prime; /* TODO: Set all the elements to PRIME. Remember, the 1st element is numbers[0] and the last is numbers[999] */ /* TODO: 0 and 1 aren't prime, so set numbers[0] and numbers[1] to NONPRIME */ next_prime = 2; do{ mark_multiples(next_prime); next_prime = get_next_prime(next_prime); } while(next_prime < 1000); /* TODO: Print out the indices of elements which are still set to PRIME */ exit(0); }

The `

`TODO`' lines describe what code you need to add in.You can speed up this program considerably by replacing

`1000`where appropriate by something smaller. See online for details.