Lawrence Technological University
College of Arts and Science
Department of Mathematics and Computer Sciences

Introduction to C, MCS 1142

Syllabus | Handouts | Assignments | Lecture Notes

A program that prints the ASCII code

The following is the program that prints an ASCII chart, similar to Appendix A combined with Appendix D - Table 1. It has some examples of many things covered in this course.

/* ascii.c
   program to print an ASCII table
   jmmiller@ltu.edu
   Rev. 1/4/03 */
#include <stdio.h>

char *nonprinting[] = {  // characters 0 - 32 and 127
  "NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL",
  "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
  "DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB",
  "CAN","EM", "SUB","ESC","FS", "GS", "RS", "US",
  "SP","DEL"
};

char *binary(int i) // low order 8 bits to an 8 character string
{
  static char b[9];
  char *p = b;
  int mask = 0x80; // 1000 0000 binary
  while (mask) {
    *p++ = mask & i ? '1' : '0';
    mask >>= 1;  // shift mask bit to the right 1 place
  }
  *p = 0;  // terminate the string
  return b;
}

char *charName(int c) // print the character or the ASCII name
{
  static char n[6];
  int i;
  if (c <= 32) {                    // non printing characters
    for (i = 0;nonprinting[c][i];i++)  // copy the ASCII abreviation
      n[i] = nonprinting[c][i];
    n[i] = 0;                          // terminate the string
  } else if (c == 127) {               // DEL
    sprintf(n,"%s",nonprinting[33]);    // use library function
  } else {     // regular character
    n[0] = c;
    n[1] = 0;                          // terminate the string
  } 
  return n;
}

void printRow(int c)
{
  fprintf(stdout,"   %-6s %-7d %-7x %-6o   %s\n", charName(c),c,c,c,binary(c));
}

int main()
{
  int i;
  /* print the captions */
  printf("An ASCII Chart\n");
  printf("%9s %7s %7s %6s   %s\n",
         "Character","Base 10","Base 16","Base 8","Base 2");
  for (i = 0;i <= 127;i++)
    printRow(i);
  return 0;
}

Revised January 4, 2003