C programming examples
Prof. Gustavo Alonso
Computer Science Department
ETH Zürich
alonso@inf.ethz.ch
http://www.inf.ethz.ch/department/IS/iks/
©Gustavo Alonso, ETH Zürich. C programming examples 2
Programming examples in C
o Dynamic queue
o Use of timing functions
o Generating random numbers
o Arguments and main
o Use of static
o Counting bits
Programming examples taken from the on-line book:
Programming in C
UNIX System Calls and Subroutines using C
http://www.cs.cf.ac.uk/Dave/C/CE.html
©Gustavo Alonso, ETH Zürich. C programming examples 3
do {
Menu (&choice);
switch (choice) {
case 1:
printf ("Enter data item value to add ");
scanf ("%d", &data);
listpointer = AddItem (listpointer, data);
break;
case 2:
if (listpointer == NULL)
printf ("Queue empty!\n");
else
listpointer = RemoveItem (listpointer);
break;
case 3:
PrintQueue (listpointer); break;
case 4:
break;
default:
printf ("Invalid menu choice - try again\n");
break;
}
} while (choice != 4);
ClearQueue (listpointer);
exit (0);
} /* main */
/* */
/* queue.c */
/* Demo of dynamic data structures in C */
#include <stdio.h>
#define FALSE 0
#define NULL 0
typedef struct {
int dataitem;
struct listelement *link;
} listelement;
void Menu (int *choice);
listelement * AddItem (listelement * listpointer, int data);
listelement * RemoveItem (listelement * listpointer);
void PrintQueue (listelement * listpointer);
void ClearQueue (listelement * listpointer);
main () {
listelement listmember, *listpointer;
int data, choice;
listpointer = NULL;
©Gustavo Alonso, ETH Zürich. C programming examples 4
void Menu (int *choice) {
char local;
printf ("\nEnter\t1 to add item,\n\t2 to remove item\n\
\t3 to print queue\n\t4 to quit\n");
do {
local = getchar ();
if ((isdigit (local) == FALSE) && (local != '\n')) {
printf ("\nyou must enter an integer.\n");
printf ("Enter 1 to add, 2 to remove, 3 to print, 4 to quit\n");
}
} while (isdigit ((unsigned char) local) == FALSE);
*choice = (int) local - '0';
}