home *** CD-ROM | disk | FTP | other *** search
/ ftp.disi.unige.it / 2015-02-11.ftp.disi.unige.it.tar / ftp.disi.unige.it / pub / .person / CataniaB / teach-act / esempi / Comp-Sep / table.c < prev    next >
C/C++ Source or Header  |  1999-03-11  |  948b  |  57 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "table.h"
  4.  
  5. #define MAX_SIZE 100
  6.  
  7. table newTab(void)
  8. {
  9.   table t;
  10.   int i;
  11.  
  12.   t = (table) calloc(MAX_SIZE,sizeof(struct tab));
  13.   for (i=0;i<MAX_SIZE;i++)
  14.     t[i].key=t[i].val=0;
  15.   return t;
  16.  
  17. void insert(table t,int key, int val)
  18. {
  19.   int i=0;
  20.  
  21.   /* find the key */
  22.   while(i<MAX_SIZE && t[i].val && t[i].key!=key)
  23.     i++;
  24.   if (i==MAX_SIZE) /* error: full table */
  25.     {
  26.       printf("\nError: table is full\n");
  27.       return;
  28.     }
  29.   if (!t[i].val) /* create a new association */
  30.     t[i].key=key;
  31.   t[i].val=val;  /* update the association */
  32. }
  33.  
  34. int getVal(table t,int key)
  35. {
  36.   int i=0;
  37.  
  38.   /* find the key */
  39.   while(i<MAX_SIZE && t[i].val && t[i].key!=key)
  40.     i++;
  41.   if (!t[i].val) /* key not found */
  42.     return 0;
  43.   else return t[i].val;
  44. }
  45.  
  46. void print(table t)
  47. {
  48.   int i=0;
  49.  
  50.   while(i<MAX_SIZE && t[i].val)
  51.     {
  52.       printf("Value at key %d is %d\n",t[i].key,t[i].val);
  53.       i++;
  54.     }
  55. }
  56.