C programming Language – Code snippets

C Programming Language, 2nd Edition

Compiling and running the sample codes using gcc :

gcc sample.c -o sample
./sample

Chapter 3 – Control Flow

1. Trim whitespace

#include<stdio.h>
#include<string.h>


int main()
{
  int n,i=0;
  char s[]="   HELLO THERE    ";
  printf("Before trim:%s\n",s);
  for(n=strlen(s)-1; n>=0; n--)
   if(s[n]!=' ' && s[n]!='\t' && s[n]!='\n') break;
  s[n+1]='\0';
  while(isspace(s[i++]));
  i=0;
  while(s[i]!='\0') s[i++];
  s[i]='\0';
  printf("After trim:%s\n",s);
  return n;
}

2. Binary search

#include<stdio.h>


int binsearch(int x, int v[], int n);

int main(int argc, char *argv[])
{
  int size=argc,found;
  int counter=0,x, v[size-2];
  x=atoi(argv[size-1]);
  if (argc<3) {printf("Usage: progname integer-list integer-to-be-searched\n"); return -1; }
  while(counter <= size-3)
  { v[counter]=atoi(argv[counter+1]);
    counter++; }
(found=binsearch(x,v,size-2))!=-1 ? printf("Found=%d\n",v[found]): printf("Not found\n");
 return 0;
}

int binsearch(int x, int v[], int n)

{
   int low, high, mid;
   low=0;
   high=n-1;
   while(low<=high)
     {
       mid=(low+high)/2;
       if(x < v[mid])  high=mid-1;
       else if (x > v[mid]) low=mid+1;
       else
         return mid;
     }
return -1;
}

3. Integer to string with argument parsing.


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define  SIZE  10

void itoa(int n, char s[]);
void reverse(char s[]);
int main(int argc, char *argv[])
 {
   char s[SIZE];
   int n;
   if(argc!=2) { printf("Usage: progrname integer\n"); return -1; }
   n=atoi(argv[1]);
   itoa(n,s);
   printf("String:%s\n",s);
   return 0;

 }

void itoa(int n, char s[])
 {
    int i, sign;
    if((sign=n)<0) n=-n;
    i=0;
    do {
         s[i++]=n%10 + '0';
       } while( (n/=10)>0);

 if (sign<0) s[i++]='-';
 s[i]='\0';
 reverse(s);
}

void reverse(char s[])
{
 int c, i, j;

  for(i=0,j=strlen(s)-1; i<j; i++,j--)
   {
        c=s[i];  s[i]=s[j];  s[j]=c;
   }
}

4. Reverse string and convert integer to string

#include<stdio.h>
#include<string.h>
#define SIZE 1000 

void reverse(char s[]);
void itoa(int n, char s[]);

int main()
{
  char s[SIZE]="HELLO WORLD!!";
  reverse(s);
  printf("%s\n",s);
  itoa(87690,s);
  printf("%s\n",s);
return 0;
}

void reverse(char s[])
{
 int c, i, j;

  for(i=0,j=strlen(s)-1; i<j; i++,j--)
   {
        c=s[i];  s[i]=s[j];  s[j]=c;
   }
}

void itoa(int n, char s[])
{
  int i, sign;
  if((sign=n)<0) n=-n;
  i=0;
      do {
           s[i++] = n%10 + '0';
         } while((n/=10)>0);
  if(sign<0) s[i++] = '-';
  s[i]='\0';
  reverse(s);
}

5. Command line argument parsing


#include<stdio.h>

int main(int argc, char *argv[])
{
  int i,counter;
  printf("Number of arguments:%d\n",argc);
  printf("Arguments character-by-character\n");
   for(counter=0;counter < argc ; counter++)
    { while(*argv[counter])
      printf("%c ",*argv[counter]++);
      printf("\n");
    }

printf("\n");
return 0;
}

6. Reverse a string

#include<stdio.h>
#include<string.h>
#define SIZE 1000 

void reverse(char s[]);

int main()
{
  char s[SIZE]="HELLO WORLD!";
  reverse(s);
  printf("%s\n",s);

return 0;
}

void reverse(char s[])
{
 int c, i, j;

  for(i=0,j=strlen(s)-1; i<j; i++,j--)
   {
        c=s[i];  s[i]=s[j];  s[j]=c;
   }
}

7. Sorting with shell sort method.


#include<stdio.h>
#define  SIZE  10
void shellsort(int v[], int n);

int main()
{
int counter;
int v[SIZE]={8,13,9,45,90,24,56,11,20,10};
shellsort(v,SIZE);
for(counter=0; counter<SIZE; counter++)
  printf("%d  ",v[counter]);
printf("\n");
return 0;
}

void shellsort(int v[], int n)
{
   int gap, i, j, temp;
   for(gap=n/2; gap>0; gap/=2)
     for(i=gap; i<n; i++)
       for(j=i-gap; j>=0 && v[j]>v[j+gap]; j-=gap)
        {
           temp=v[j];
           v[j]=v[j+gap];
           v[j+gap]=temp;
        }
}

8. using switch case


#include<stdio.h>

int main()
{
  int c, i, nwhite, nother,alpha, ndigit[10];
  nwhite=nother=alpha=0;
  for(i=0; i<10; i++) ndigit[i]=0;
  while((c=getchar())!=EOF)
  {
   switch(c)
    {
      case '0': case '1': case '2': case '3': case '4': case '5':
      case '6': case '7': case '8': case '9':
        ndigit[c-'0']++; break;
      case ' ': case '\n': case '\t': nwhite++; break;
      default:
          nother++; break;
     }
   }
printf("Digits =");
for(i=0; i<10; i++) printf(" %d", ndigit[i]);
printf(", white space =%d, other = %d\n", nwhite, nother);
return 0;
}

9. Double input – strip out non integers

#include<stdio.h>
#include<ctype.h>

#define  SIZE  10

int atoi(char s[]);

int main(int argc, char *argv[])
{
  int counter=0;
  char s[SIZE];
  if (argc!=2) {
    printf("Usage: progname integer\n");
    return 1;
  }
  while(*argv[1])  s[counter++]=(*argv[1]++);
  printf("Twice Result=%d\n",2*atoi(s));
return 0;
}
int atoi(char s[])
{
  int n, i,sign;

 for(i=0; isspace(s[i]); i++);

sign=(s[i]=='-')? -1: 1;
if(s[i] == '+' || s[i] == '-') i++;
 for(n=0; isdigit(s[i]); i++)
   n=10*n + (s[i]-'0');

return sign*n;
}

Reference –

https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628#reader_0131103628

C programming Language – Code snippets

C Programming Language, 2nd Edition

Compiling and running the sample codes using gcc :

gcc sample.c -o sample
./sample

Chapter 2 – Types, Operators and Expressions

1.Convert to lower case.

#include<stdio.h>

int main(int argc, char *argv[])

{

  while(*argv[1])
   {
     if(*argv[1] >='A' && *argv[1] <='Z') { putchar(*argv[1] + 'a' -'A'); *++argv[1]; }
     else
      {putchar(*argv[1]); *++argv[1]; }
   }

printf("\n");
return 0;
}

2. Get bits


#include<stdio.h>

unsigned getbits(unsigned x,int p, int n);

int main()

{
   int x=16;
   printf("%d\n",getbits(x,4,3));

return 0;
}

unsigned getbits(unsigned x, int p, int n)
 {
   return ( x >> (p+1-n)) & ~(~0 << n);
 }

3. Count one bits


#include<stdio.h>

int bitcount(unsigned x);
int main()

{
  unsigned short x=38;

  printf("%d has %d 1 bits\n",x,bitcount(x));
  return 0;
}

int bitcount(unsigned x)
 {
   int b;
   for(b=0; x!=0; x>>=1)
    if (x&1) b++;
  return b;
}

4. Remove character from string



#include<stdio.h>

int main(int argc, char *argv[])

{


if (argc !=3)  { printf("usage: del string char\n"); return -1;}

while(*argv[1])

{
   if(*argv[1] != *argv[2]) { putchar(*argv[1]); *++argv[1]; }
   else
   { *++argv[1]; continue; }
}
printf("\n");
return 0;

}

5. Convert x to binary


#include<stdio.h>
#define  LEN 16
int main()

{
  int x=112,counter=0;
  int binary[LEN]={0};
  while(x)
   {
     binary[counter]=x%2; x/=2; counter++;
   }
while(counter>=0) { printf("%d",binary[counter]); counter--; }
printf("\n");
return 0;
}

6. Convert char to integer

#include<stdio.h>

#define NUM 1

int main(int argc, char *argv[])

{
 int counter=1,n=0;

 if(argc!=2) { printf("usage: atoi arglist\n"); return -1;}

 while(*argv[NUM])
   {
      if(*argv[NUM]>='0' && *argv[NUM]<='9') { n=10*n+(*argv[NUM]-'0'); *++argv[NUM]; }
      else
       { *++argv[NUM]; continue; }
   }
 printf("number=%d\n",n);
 return 0;

 }

Reference –

https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628#reader_0131103628

C programming Language – Code snippets

C Programming Language, 2nd Edition

Compiling and running the sample codes using gcc :

gcc sample.c -o sample
./sample

Chapter 1 – Introductory tutorial : Input/output, characters, strings

0. Hello World!

#include<stdio.h>

int main()

{

  printf("Hello World\n");
  return 0;
}

1. Word counter


/* word counter */
#include<stdio.h>

#define  IN 1  //inside a word
#define  OUT   0  //outside a word

int main()

{
  int c,nl,nw,nc,state;
  state=OUT;
  nl=nw=nc=0;

  while((c=getchar())!=EOF)
   {
      ++nc;
      if(c=='\n') ++nl;
      if (c==' ' || c == '\n' || c=='\t') state=OUT;
      else if (state==OUT)
         {
           state=IN;
           ++nw;
          }
        }
      printf("lines=%d words=%d characters=%d\n",nl,nw,nc);
 return 0;
}

2. Convert Fahrenheit to Celsius


#include<stdio.h>

#define  LOWER 0
#define  UPPER 300
#define  STEP  20

int main()

  {
     int fahr;
     for (fahr = LOWER; fahr <= UPPER; fahr=fahr + STEP)
         printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
     return 0;
 }


3. Count characters


/* character counter */
#include<stdio.h>

int main()

{
   short int nc;
   for(nc=0; getchar()!=EOF ; ++nc);
   printf("%d\n",nc);
   return 0;
}

4. Count characters by type – digits, white spaces etc.


/* count digits, white space, others */
#include<stdio.h>

int main()
 {
   int c,i,nwhite,nother;
   int ndigit[10];

   nwhite=nother=0;
   for(i=0; i < 10; ++i)  ndigit[i]=0;

   while((c=getchar())!=EOF)
     if(c>='0' && c<='9') ++ndigit[c-'0'];
     else if (c==' ' || c=='\n' || c=='\t') ++nwhite;
     else  ++nother;

   printf("digits=");
   for(i=0;i<10;++i) printf(" %d",ndigit[i]);
   printf(",white space=%d, other=%d\n",nwhite,nother);

return 0;
}

5. Copy input to output terminal


/* copy input to output 1 */
#include<stdio.h>

int main()

{
   int c;
   c = getchar();
   while ( c!=EOF)
     {
       putchar(c);
       c = getchar();
     }
 return 0;
}

6. Copy input to output terminal (shorter version)

/* copy input to output */
#include<stdio.h>

int main()
{
   int c;
   while((c=getchar())!=EOF)
     putchar(c);
   return 0;
}

7. Print longest line


#include<stdio.h>

#define  MAXLINE  1000  /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */

int main()

{
  int len;  /* current line length */
  int max;  /* maximum length seen so far */
  char line[MAXLINE];   /* current input line */
  char longest[MAXLINE];   /*longest line saved here */

  max=0;
  while((len=getline(line,MAXLINE))>0)
    if(len>max)
       { max=len;
         copy(longest,line);
       }
 if(max>0)  /*there was a line*/
  printf("Longest Line from input is:\n%s\n",longest);
  printf("Line length is: %d characters\n",max);

return 0;
}


/*getline: read a line into s, return length */

int getline(char s[], int lim)
{
  int c,i;
  for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
   s[i]=c;
 if(c=='\n') {
  s[i]=c;
  ++i;
  }
 s[i]='\0';
 return i;
}

/*copy: copy 'from' into 'to'; assume 'to' is big enough */

void copy(char to[], char from[])
{
  int i;
  i=0;
  while((to[i]=from[i]) != '\0')
    ++i;
}

8. Print longest line – improved


#include<stdio.h>

#define  MAXLINE  1000  /* maximum input line length */

int max;
char line[MAXLINE];
char longest[MAXLINE];

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */

int main()

{
  int len;  /* current line length */
  extern int max; /* maximum length seen so far */
  extern char longest[MAXLINE];  /*longest line saved here */

  max=0;
  while((len=getline(line,MAXLINE))>0)
    if(len>max)
       { max=len;
         copy(longest,line);
       }
 if(max>0)  /*there was a line*/
  printf("Longest Line from input is:\n%s\n",longest);
  printf("Line length is: %d characters\n",max);

return 0;
}


/*getline: read a line into s, return length */

int getline(char s[], int lim)
{
  int c,i;
  extern char line[];
  for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
   s[i]=c;
 if(c=='\n') {
  s[i]=c;
  ++i;
  }
 s[i]='\0';
 return i;
}

/*copy: copy 'from' into 'to'; assume 'to' is big enough */

void copy(char to[], char from[])
{
  int i;
  extern char line[], longest[];
  i=0;
  while((to[i]=from[i]) != '\0')
    ++i;
}

9. Power function


#include<stdio.h>

int power(int m, int n);

/* test power function */

int main()

{
  int i;
  for(i=0; i<10; ++i)
   printf("%d %d %d\n",i,power(2,i),power(-3,i));
 return 0;
}

int power(int base, int n)
 {
   int i,p=1;
   for(i=1;i<=n;++i)
     p*=base;
   return p;
 }

10. Reverse string


#include<stdio.h>

#define  MAXLINE  1000

int size=0;
void reverse(char line[], int lim);
int main()

{ extern int size;
  char line[MAXLINE];
  reverse(line,MAXLINE);
  while(size) putchar(line[--size]);
  printf("\n");
  return 0;
}

void reverse(char line[], int lim)

{
 extern int size;
 int c;
 while((c=getchar())!=EOF ) line[size++]=c;
 line[size]='\0';

}

11. Get digits only


#include<stdio.h>

int atoi(char s[]);

int main()

{
  char str[]="12a4c5 ";
  int i=0,n=0;

 while(str[i]!='\0')
   {
      if(str[i]>='0' && str[i]<='9') { n=10*n+(str[i]-'0'); i++; }
      else
       { i++; continue; }
   }
 printf("number=%d\n",n);
 return 0;

 }

12. Fahrenheit to Celsius table

/* print Fahrenheit-Celsius table for fahr =0,20,40,....,300 */

#include<stdio.h>

int main()

{
  int fahr, celsius;
  int lower, upper, step;
  lower = 0;
  upper = 300;
  step = 20;

  fahr = lower;
  while( fahr <= upper)
   {
      celsius = 5 * (fahr - 32) / 9;
      printf("%d\t%d\n", fahr, celsius);
      fahr = fahr + step;
   }

return 0;
}

Reference –

https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628#reader_0131103628

Getting yourself familiar with basic programming skills doesn’t hurt. In fact, there are times when you will desperately need to automate a task for some seemingly simple job, and yet not find the right tools out there which cater your needs. It is not about writing thousands of lines of code and designing some user interface, just a dozen or two lines might serve well at times. Here is a list of C codes taken from the book ‘C programming Language’ by K&R and some of the codes might have been changed by me while practicing.

1. Introductory Tutorial – Input/output, characters, strings

2. Types, Operators and Experessions – Upper/lower case conversion, binary operators

3.  Control Flow – If/else, do/while, binary search, sorting, argument list

4.  Functions and Program structure – macros, polish calculator, pattern searching, quick sort

5. Pointers and Arrays – command line argument, find, sort, memory allocation

6.  Structures – self referential arrays, word key counter

7.  Input/Output – file copying, calculator, sscanf

8.  The UNIX System Interface – memory allocations, file & directory listing