Tilbage til slide -- Tastaturgenvej: 'u'  forrige -- Tastaturgenvej: 'p'                chars/number-in-base.c - Et C program der omregner et tal fra titalsystemet til et andet talsystem og udskriver resultatet.Lektion 10 - slide 10 : 51
Program 2

#include <stdio.h>
#define MAX_BASE_SUPPORTED 36

void print_in_base(int, int);

int main(void) {
  int i, n, base;

  printf("THIS PROGRAM CONVERTS DECIMAL NUMBERS " 
         "TO NUMBERS IN ANOTHER BASE (FROM 2 TO 36).\n\n");

  for (i = 1; i <= 5; i++){
    printf("Enter positive decimal number "
           "and number base (at least two): ");
    scanf(" %d %d", &n, &base);

    if ((n > 0) && (base >= 2) && (base <= MAX_BASE_SUPPORTED)){
      print_in_base(n, base); 
      printf("\n");
    }
    else
      printf("Illegal input. Try again\n");
  }
  
  return 0;
}

/* Convert the decimal number n to base and print the result */
void print_in_base(int n, int base){
  int ciffer;

  if (n > 0){
    ciffer = n % base;   /* find least significant ciffer */

    /* RECURSIVELY, find and print most significant ciffers */
    print_in_base(n / base, base);  

    /* print least significant ciffer */    
    if (ciffer >= 0 && ciffer <= 9)
      putchar('0' + ciffer);
    else if (ciffer >= 10 && ciffer <= MAX_BASE_SUPPORTED)
      putchar('a' + ciffer - 10);
    else putchar('?');
  } 
}