Department of Engineering

Next: Exercises 2 Up: Sample answers to exercises Previous: Sample answers to exercises   Contents

## Exercises 1

• ```#include <stdio.h>
#include <stdlib.h>

int odd(int number){
/* return 0 if number is even, otherwise return 1 */
if ( (number/2)*2 == number)
return 0;
else
return 1;
}

int main(){
int i;
i = 7;
printf("odd(%d) = %d\n",i,odd(i));
}
```
• ```#include <stdio.h>
#include <stdlib.h>

void binary(unsigned int number){
/* print decimal `number' in binary */
unsigned int power_of_2;
power_of_2=1;
/* Find the greatest power of 2 which isn't more
than the number
*/
while (power_of_2<= number)
if (power_of_2*2>number)
break;
else
power_of_2=power_of_2*2;

/* Now print out the digits */
while(power_of_2>0){
if( number/power_of_2 == 1){
printf("1");
number = number - power_of_2;
}
else
printf("0");
power_of_2=power_of_2/2;
}
printf("\n");
}

int main(){
unsigned int i;
i=187;
printf("%d in binary is ",i);
binary(i);
}
```
• ```#include <stdio.h>
#include <stdlib.h>
void base(unsigned int number, unsigned int base){
/* Print 'number' to a specified base */
unsigned int power_of_base;
power_of_base=1;
/* Find the greatest power of 'base' which isn't more
than the number
*/
while (power_of_base<= number){
if (power_of_base*base>number)
break;
else
power_of_base=power_of_base*base;
}

/* Now print out the digits */
while(power_of_base>0){
printf("%1d", number/power_of_base);
number = number - power_of_base * (number/power_of_base);
power_of_base=power_of_base/base;
}
printf("\n");
}

int main(){
base(87,2);
base(100,8);
}
```
• ```#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){

/* Set all elements which represent multiples of num to NONPRIME */
int multiple = num *2;
while (multiple < 1000){
numbers[multiple] = NONPRIME;
multiple = multiple + num;
}
}

int get_next_prime(int num){
/* find the next prime number after `num' */
if (answer == 1000)
break;
}
}

main(){
int i;
int next_prime;

/* Set all the elements to PRIME.*/
for(i=0;i<1000;i++){
numbers[i] = PRIME;
}

/* 0 and 1 aren't prime, so set numbers[0] and numbers[1] to false */
numbers[0] = NONPRIME;
numbers[1] = NONPRIME;

next_prime = 2;
do{
mark_multiples(next_prime);
next_prime = get_next_prime(next_prime);
}while(next_prime < 1000);

/* Print out the indices of elements which are still set to PRIME */
for(i=0;i<1000;i++)
if (numbers[i] == PRIME)
printf(" %d  ",i);

exit(0);
}
```

Tim Love 2010-04-27