Archive for the ‘ c-programming ’ Category

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 4 – Functions and Program structure


1. A conditional in the C preprocessor


#include<stdio.h>

#define SYSTEM 5

#if SYSTEM == 1
#define HDR 10
#elif SYSTEM == 2
#define HDR 20
#elif SYSTEM == 3
#define HDR 30
/*#else
#define HDR 0*/
#endif

#if !defined(HDR)
#define HDR 50
#endif

int main()

{
printf("HDR = %d \n", HDR);
return 0;
}

 

2. Macro definitions


#include<stdio.h>

#define max(A,B) ((A)>(B) ? (A) : (B))
#define forever for(;;)
#define square(x) ((x)*(x))
#define dprint(expr) printf(#expr " = %g\n", expr)
#define paste(front, back) front ## back

int main()

{
char name[]="daniel";
int counter=0,x=4,y=2;
printf("Max=%d\n",max(8,9));

forever
{
printf(" %d ", counter);
if ( counter++ >= 10) break;
}

printf("\n");

printf("Square of 4 is %d\n",square(4));

dprint(x/y);

return 0;
}

 

3. Pattern matching


#include<stdio.h>

#define MAXLINE 1000

int getline(char line[], int max);
int strindex(char source[], char searchfor[]);

char pattern[]="dan";

int main()
{
char line[MAXLINE];
int found=0;
while(getline(line,MAXLINE)>0)
if(strindex(line,pattern) >= 0)
{
printf("%s",line);
found ++;
}
return found;
}

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

int strindex(char s[], char t[])
{
int i,j,k;
for(i=0; s[i]!='\0'; i++)
{
for(j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if(k>0 && t[k] == '\0')
return i;
}
return -1;
}

 

4. Reverse polish calculator


/*reverse Polish calculator */
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

#define MAXOP 100
#define NUMBER '0'
#define MAXVAL 100
#define BUFSIZE 100

int getch(void);
void ungetch(int);
int getop(char []);
void push(double);
double pop(void);

int sp = 0;
double val[MAXVAL];
char buf[BUFSIZE];
int bufp=0;

int main()
{
int type;
double op2;
char s[MAXOP];

while((type=getop(s)) != EOF)
{
switch(type)
{
case NUMBER: push(atof(s)); break;
case '+': push(pop() + pop()); break;
case '-': op2=pop(); push(pop() - op2); break;
case '*': push(pop() * pop()); break;
case '/':
op2=pop();
if(op2 != 0.0) push(pop()/op2);
else
printf("Error: zero divisor\n");
break;
case '\n': printf("\t%.8g\n", pop()); break;
default: printf("Error: unknown command %s\n", s); break;
}
}

return 0;
}

void push(double f)
{
if(sp < MAXVAL) val[sp++] = f;
else
printf("Error: stack full, can't push %g\n", f);
}

double pop(void)
{
if(sp > 0)
return val[--sp];
else
{
printf("Error: stack empty\n");
return 0.0;
}
}

int getop(char s[])
{
int i, c;

while((s[0] = c = getch()) == ' ' || c == '\t') ;

s[1] = '\0';
if(!isdigit(c) && c!= '.') return c;
i=0;
if(isdigit(c))
while(isdigit(s[++i] = c= getch())) ;
if ( c=='.')
while(isdigit(s[++i] = c = getch())) ;
s[i] = '\0';
if ( c!= EOF) ungetch(c);
return NUMBER;
}

int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
if (bufp >= BUFSIZE) printf("ungetch: too many characters\n");
else
buf[bufp++]=c;
}

 

5. Quick sort


#include<stdio.h>

void qsort(int v[], int left, int right);

int main()

{

int i, v[]={9,5,8,12,56,7,1,19,27,99,27,13,3};

for(i=0; i<13; i++) printf(" %d ",v[i]);
printf("\n");

qsort(v,0,12);

for(i=0; i<13; i++) printf(" %d ",v[i]);
printf("\n");

return 0;
}

void qsort(int v[], int left, int right)
{
int i, last;
void swap(int v[], int i, int j);

if(left >= right) return;
swap(v, left, (left + right)/2);

last = left;

for(i=left+1; i<=right; i++)
if(v[i] < v[left]) swap(v,++last, i);

swap(v, left, last);
qsort(v, left, last-1);
qsort(v, last+1, right);

}

void swap(int v[], int i, int j)
{
int temp;

temp = v[i];
v[i] = v[j];
v[j] = temp;
}

 

6. Rudimentary calculator


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

#define MAXLINE 100

double atof(char s[]);
int getline(char line[], int max);

int main()
{

double sum, atof(char []);
char line[MAXLINE];
int getline(char line[], int max);

sum=0;
while(getline(line,MAXLINE) > 0)
printf("\t%g\n", sum+=atof(line));

return 0;
}

double atof(char s[])
{

double val, power;
int i, sign;
for (i=0; isspace(s[i]); i++);

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

if(s[i] == '.') i++;

for(power=1.0; isdigit(s[i]); i++)
{
val = 10.0*val + (s[i] - '0');
power*=10;
}

return (sign*val/power);

}

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

}

 

7. ASCII string to float conversion


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

int main()
{
double val, power;
int i, sign;
char s[]=" -23.590 ";

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

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

if(s[i] == '.') i++;

for(power=1.0; isdigit(s[i]); i++)
{
val = 10.0*val + (s[i] - '0');
power*=10;
}

printf("Value = %f\n", (sign*val/power));
return 1;
}

 

References –

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

C programming tutorial

Getting yourself familiar with basic programming skills is quite helpful these days. 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 TutorialInput/output, characters, strings

 

2. Types, Operators and ExperessionsUpper/lower case conversion, binary operators

 

3.  Control FlowIf/else, do/while, binary search, sorting, argument list

 

4.  Functions and Program structuremacros, polish calculator, pattern searching, quick sort

 

5. Pointers and Arrayscommand line argument, find, sort, memory allocation

 

6.  Structuresself referential arrays, word key counter

 

7.  Input/Outputfile copying, calculator, sscanf

 

8.  The UNIX System Interfacememory allocations, file & directory listing

 


 

Reference book –