C: Some examples

By Abhishek

 
 
 

Some C code that I wrote when I was learning C

Example 1: 
/* vis: make funny characters visible */
#include <stdio.h>
#include <ctype.h>
main(argc, argv)
  int argc;
  char *argv[];         /*  argv[0] is the command name itself so the
                            first argument is argv[1] */
{
        int c;
        int strip = 0;
        if (argc > 1 && strcmp(argv[1],"-s") == 0 )
                strip = 1;
        while ((c = getchar()) != EOF)
                if (isascii(c) && (isprint(c) || c=='\n' || c=='\t' || c==' '))
                        putchar(c);
                else if (strip == 0)
                        printf("\\%03o", c);
        putchar('\n');
        exit(0);         
}
Go To Top

Example 2: 
/*
   visf: make funny characyers visible
   Use -s to strip of printing characters
   The input must be a file(s)
*/
#include <stdio.h>
#include <ctype.h>
int strip = 0;          /* discard special characters when = 1 */
main(argc, argv)
     int argc;
     char *argv[];
{
        int i;
        FILE *fp;       /* Declare a pointer to a file */
        while (argc > 1 && argv[1][0] == '-')
        {
                switch (argv[1][1])
                {
                        case 's':    
                                strip = 1;
                                break;
                        default:
                                fprintf(stderr, "%s: unknown arg %s\n",
                                argv[0], argv[1]);
                                exit(1);
                }
                argc--;
                argv++;
        }
        if (argc == 1)
                vis(stdin);
        else
                for (i = 1; i < argc; i++)
                        if ((fp=fopen(argv[i], "r")) == NULL)
                        {
                                fprintf(stderr, "%s: cannot open %s\n",
                                   argv[0], argv[i]);
                                exit(1);
                        }
                        else              
                        {
                                vis(fp);
                                fclose(fp);
                        }
        exit(0);
}
vis(fp)
  FILE *fp;
{
        int c;
        while (( c = getc(fp)) != EOF)
                if (isascii(c) && (isprint(c) || c=='\n' || c=='\t' ||
                                                 c==' '))
                        putchar(c);
                else if (!strip)
                        printf("\\%03o", c);
        putchar('\n');
}                  
DEMO 2:
$ a.out -x
a.out: unknown arg -x
$ a.out -s planet
-s: cannot open planet
$ cat planet.dat
Earth@øið@# A‰7KÇsaturnvenus@333333@$
$ a.out -s planet.dat
Earth@i@#A7Ksaturnvenus@333333@
$ a.out planet.dat
Earth\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\00
0@\370i\360\000\000\000\000@#\240A\2117K\307saturn\000\000\000\000\000\000\000\0
00\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\0
00\000\000\000\000\000\000venus\000\000\000\000\000\000\000\000\000\000\000\000\
000\000\000\000\000\000\000@\013333333@\024\000\000\000\000\000\000
Go To Top

Example 3:
/* p: print input in chunks */
#include <stdio.h>
#define PAGESIZE 22
char *progname;         /* program name for error message */
main(argc, argv)
  int argc;
  char *argv[];         /*  argv[0] is the command name itself so the
                            first argument is argv[1] */
{
        int i;
        FILE *fp, *efopen();
        progname = argv[0];
        if (argc == 1)
                print(stdin, PAGESIZE);
        else
                for (i = 1; i < argc; i++)
                {
                        fp = efopen(argv[i], "r");  
                        print(fp, PAGESIZE);
                        fclose(fp);
                }
        exit(0);
}
/* function to open the file */
FILE *efopen(file, mode)
   char *file, *mode;
{
        FILE *fp, *fopen();
        extern char *progname;
        if ((fp = fopen(file, mode)) != NULL)
                return fp;
        fprintf(stderr, "%s: cannot open file %s mode %s \n",
                progname, file, mode);
        exit(1);               
}
/* function to print fp in pagesize chuncks */
print(fp, pagesize)
  FILE *fp;
  int pagesize;
{
        static int lines = 0;           /* number of lines so far */
        char buf[BUFSIZ];
        while (fgets(buf, sizeof buf, fp) != NULL)
                if ( ++lines < pagesize)
                        fputs(buf, stdout);
                else
                {
                        buf[strlen(buf) - 1] = '\0';
                        fputs(buf, stdout);
                        fflush(stdout);
                        ttyin();
                        lines = 0;
                }
}                 
/* function to process response from terminal */
ttyin()
{
        char buf[BUFSIZ];
        FILE *efopen();
        static FILE *tty = NULL;        /* static to retain value */
        if (tty == NULL)                /* Open in first call only */
                tty = efopen("/dev/tty", "r");
        if (fgets(buf, BUFSIZ, tty) == NULL || buf[0] == 'q')
                exit(0);
        else
                return buf[0];          /* ordinary line */
}
Go To Top

Example 4:
#include <stdio.h>
main()
{
  char name[26];
  puts("What is your name: ");          /* write string to stdout */
  gets(name);                           /* Get string from stdin */
  puts("Hello. How are you ?? ");
  puts(name);
}
Demo 4:
$ a.out
What is your name:
Abhishek
Hello. How are you ??
Abhishek
Go To Top

Example 5:
#include <stdio.h>
main()
{
  char grade;
  printf("Please enter the grade: ");
  grade=getchar();
  fflush(stdin);
  switch (grade)
  {
    case 'A':
      printf("The HRA percentage for grade %c is 45\n", grade);
      break;
    case 'B':
      printf("The HRA percentage for grade %c is 40\n", grade);
      break;
    case 'C':
      printf("The HRA percentage for grade %c is 30\n", grade);
      break;
    case 'D':
      printf("The HRA percentage for grade %c is 25\n", grade);
      break;                                           
    default:
      printf("Invalid grade %c. try again.\n", grade);
      exit(10);
  }
}
Demo 5:
$ a.out
Please enter the grade: S
Invalid grade S. try again.
$ a.out
Please enter the grade: A
The HRA percentage for grade A is 45
Go To Top

Example 6:
/* This program accepts characters from keyboard until character '!' is
   input and compares the number of vowels and consonants entered */
#include <stdio.h>
main()
{
  char input;
  int num_vowel = 0;
  int num_consonant = 0;
  printf("Please insert characters. (Enter ! to quit)\n");
  input = getchar();
  while (input != '!')
  {
    switch (input)
    {
      case 'a':
      case 'e':
      case 'i':
      case 'o':             
      case 'u':
        num_vowel++;
        break;
      default:
        num_consonant++;
        break;
    }
    input = getchar();
  }
  printf("Number of vowels: %d\n", num_vowel);
  printf("Number of consonants: %d\n", num_consonant);
}
Demo 6:
$ a.out
Please insert characters. (Enter ! to quit)
dsfgsdbafdfsion!
Number of vowels: 3
Number of consonants: 12
Go To Top

Example 7:
/* Some examples of pointers */
#include "stdio.h";
main()
{
  char *name = "abhishek";      /* Declare a pointer to a char */
  char *address[3];             /* Declare an array of pointer to char */
  printf("Value of *name: %c\n", *name);
  printf("Value of name: %i\n", name);
  printf("String pointed by name: %s\n", name);
  printf("The third character in name: %c\n", *(name + 2));
  printf("The third character in name: %c\n", name[2]);
  address[0] = "Bhopal";
  address[1] = "KC";
  address[2] = "SLC";
  printf("Value of address: %i\n", address);
  printf("Value of address[0]: %i\n", address[0]);
  printf("Contents of *address: %s\n", *address);
  printf("Contents of *(address + 1): %s\n", *(address + 1));
  printf("Contents of *(address + 1): %s\n", *(address + 1));
  printf("Contents of *(address + 2): %s\n", *(address + 2));
  printf("Contents of (*(address + 1) + 1): %s\n", (*(address + 1) + 1));
}
Demo 7:
$ a.out
Value of *name: a
Value of name: 1073746112
String pointed by name: abhishek
The third character in name: h
The third character in name: h
Value of address: 2063837192
Value of address[0]: 1073746288
Contents of *address: Bhopal
Contents of *(address + 1): KC
Contents of *(address + 2): SLC
Contents of (*(address + 1) + 1): C       
Go To Top