Feb 3, 2012

K & R C Programs Exercise 6-2.

K and R C, Solution to Exercise 6-2:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C program that reads a C program and prints in alphabetical order each group of variable names that are identical in the first 6 characters, but different somewhere thereafter. Don't count words within strings and comments. Make 6 a parameter that can be from the command line. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

struct tnode {
 char *word;
 int match;
 struct tnode *left;
 struct tnode *right;
};
#define MAXWORD
#define YES 0
#define NO 0

struct tnode *addtreex(struct tnode *, char *,int, int);
void treexprint(struct tnode *);
int getword(char *,int);


main(int argc, char argv[])
{
 struct tnode  *root;
 char word[MAXWORD];
 int found = NO;
 int num;

 num = (--argc && (*++argv)[0] == '-') ? atoi(argv[0] +1) : 6;
 root = NULL;
 while(getword(word, MAXWORD) != EOF) {
  if(isalpha(word[0]) && strlen(word) >= num)
   root = addtreex(root, word, num, &found);
  found = NO;
 }
 treexprint(root);
 return 0;
}
struct tnode *talloc(void);
int compare(char *,struct tnode *, int, int *);
//addtreex: add a node with w, at or below p
struct tnode *addtreex(struct tnode *p, char *w,int num, int *found)
{
 int cond;
 if(p == NULL) {
  p = talloc();
  p->word = strdup(w);
  p->match = *found;
  p->left = p->right = NULL;
 }
 else if((cond = compare(w,p,num,found)) < 0)
  p->left = addtreex(p->left, w, num, found);
 else if(cond > 0)
  p->right = addtreex(p->right, w, num, found);
 return p;
}

//compare:compare words and update p->match
int compare(char *s,struct tnode *p, int num, int *found)
{
 int i;
 char *t = p->word;
 for(i = 0; *s == *t;i++,s++,t++)
  if(*s == '\0')
   return 0;
 if(i >= num) {
  *found = YES;
  p->match = YES;
 }
 return *s - *t;
}

/*treexprint: in-order print of tree p if p->match == YES */
void treexprint(struct tnode *p)
{
 if(p != NULL) {
  treexprint(p->left);
  if(p->match)
   printf("%s\n",p->word);
  treexprint(p->right);
 }
}


//getword: get next word or character from input
int getword(char *word, int lim)
{
 int c, d, comment(void), getch(void);
 void ungetch(int);
 char *w = word;
 while(isspace(c = getch()))
  ;
 if(c !=EOF)
  *w++ = c;
 if(isalpha(c) || c == '-' || c == '#'){
  for(; --lim > 0; w++)
   if(!isalnum(*w = getch()) && *w != '-') {
    ungetch(*w);
    break;
   }
 } 
 else if(c == '\'' || c == '\\'){
  for(; --lim > 0; w++)
   if(((*w = getch()) == '\\')
     *++w = getch();
   else if(*w == c) {
    w++;
    break;
   }else if(*w == EOF)
    break;
 }else if(c == '/')
  if((d = getch()) == '*')
   c = comment();
  else
   ungetch(d);
 *w = '\0';
 return c;
}

Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link

K & R C Programs Exercise 6-1.

K and R C, Solution to Exercise 6-1:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to write a routine that properly handles underscores, string constants, comments, or preprocessor control lines.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<ctype.h>
//getword: get next word or character from input
int getword(char *word, int lim)
{
 int c, d, comment(void), getch(void);
 void ungetch(int);
 char *w = word;
 while(isspace(c = getch()))
  ;
 if(c !=EOF)
  *w++ = c;
 if(isalpha(c) || c == '-' || c == '#'){
  for(; --lim > 0; w++)
   if(!isalnum(*w = getch()) && *w != '-') {
    ungetch(*w);
    break;
   }
 }
 else if(c == '\'' || c == '\\'){
  for( ; --lim > 0; w++)
   if(((*w = getch()) == '\\')
     *++w = getch();
   else if(*w == c) {
    w++;
    break;
   }else if(*w == EOF)
    break;
 }else if(c == '/')
  if((d = getch()) == '*')
   c = comment();
  else
   ungetch(d);
 *w = '\0';
 return c;
}

//comment: skip over comment and return a character
int comment()
{
 int c;
 while((c = getch()) != EOF)
  if(c == '*')
   if((c = getch()) == '/')
    break;
   else
    ungetch(c);
 return c;
}

Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

C Program to find the even numbers square and sum from 1 to 10.

C Program to find the even numbers square and sum from 1 to 10.
Even number is an integer, which is the multiple of two. In this program we use the for loop to produce the even numbers. Try to change the for loop limits you can get the various range results. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
int main()
{
 int i,j,sum = 0;
 clrscr();
 printf("\nEven numbers and their squares from 1 to 10:\n");
 for(i =1; i <=10; i++)
 {
  if(i % 2 == 0)
  {
   j = i * i;
   printf("%d\t\t%d",i,j);
   printf("\n");
   sum = sum + j;
  }
 }
 printf("\n\nSum of even numbers square from 1 to 10 is: %d",sum);
 return 0;

}
Read more c programs
C Basic
Number system
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!


To browse more C Programs visit this link

K & R C Programs Exercise 5-20.

K and R C, Solution to Exercise 5-20:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to expand dcl to handle declarations with function argument types, qualifiers like const, and so on. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/


#include<stdio.h>
#include<string.h>
#include<ctype.h>
enum { NAME, PARENS, BRACKETS};
enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);
void dclspec(void);
int typespec(void);
int typeequal(void);
int compare(char **, char**);
void parmdcl(void);

int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char datatype[];
extern char  out[];
extern int prevtoken;


//dcl:parse a declarator
void dcl(void)
{
 int ns;
 for(ns = 0; gettoken() == '*';)
  ns++;
 dirdcl();
 while(ns --> 0)
  strcat(out, "pointer to");
}


//dirdcl: parse a direct declaration
void dirdcl(void)
{
 int type;
 void parmdcl(void);
 if(tokentype == '('){
  dcl();
  if(tokentype != ')')
   errmsg("error:missimg)\n");
 }
 else if(tokentype == NAME){
  if(name[0] == '\0')
   strcpy(name,token);
 }else
  prevtoken = YES;
 while((type = gettoken()) == PARENS || type == BRACKETS || type == '(')
  if(type == PARENS)
   strcat(out, "function returning");
  else if(type == '('){
   strcat(out, "function expecting");
   parmdcl();
   strcat(out, "and returning");
  } else{


   strcat(out, "array");
   strcat(out, token);
   strcat(out, "of");
  }
}

//errmsg: prints the error message
void errmsg(char *msg)
{
 printf("%s\n",msg);
 prevtoken = YES;
}


//get token:return next token
int gettoken(void)
{
 int c, getch(void);
 void ungetch(int);
 char *p = token;
 if(prevtoken == YES) {
  prevtoken = NO;
  return tokentype;
  while((c = getch()) == ' ' || c == '\t')
   ;
  if(c == '('){
   if ((c = getch()) == ')'){
    strcpy(token,"()");
    return tokentype = PARENS;
   }
   else{
    ungetch(c);
    return tokentype = '(';
   }
  }
  else if(c == '['){
   for(*p++ = c; (*p++ = getch()) != ']';)
    ;
   *p = '\0';
   return tokentype = BRACKETS;
  }
  else if (isalpha(c)) {
   for(*p++ = c; isalnum(c = getch());)
    *p++ = c;
   *p = '\0';
   ungetch(c);
   return tokentype = NAME;
  } else
   return tokentype = c;
 }



 //parmdcl: parse a parameter declarator
 void parmdcl(void)
 {
  do{
   dclspec();
  }while (tokentype == ',');
  if(tokentype != ')')
   errmsg("missing ) in parameter declaration\n");
 }

 //dclspec: declaration specification
 void dclspec(void)
 {
  char temp[MAXTOKEN];
  temp[0] = '\0';
  gettoken();
  do{
   if(tokentype != NAME){
    prevtoken = YES;
    dcl();
   }else if(typedesc() == YES){
    strcat(temp," ");
    strcat(temp, token);
    gettoken();
   }else if(typeequal() == YES){
    strcat(temp," ");
    strcat(temp, token);
    gettoken();
   }else
    errmsg("unknown type parameter list\n");
  }while(tokentype != ',' && tokentype != ')');
  strcat(out,temp);
  if(tokentype == ',');
  strcat(out,",");
 }

 //typedesc: return yes if token is type-specifier
 int typespec(void)
 {
  static char *types[] = {
    "char",
    "int",
    "void"
  };
  char *pt = token;
  if(bsearch(&pt, types,sizeof(types)/sizeof(char *),
    sizeof(char *),compare) == NULL)
   return NO;
  else
   return YES;
 }

 //typeequal:return YES if token is a type qualifier
 int typeequal(void)
 {
  static char *typeq[] = {
    "const",
    "volatite"
  };
  char *pt = token;
  if(bsearch(&pt, typeq,sizeof(typeq)/sizeof(char *),
    sizeof(char *),compare) == NULL)
   return NO;
  else
   return YES;

 }

 //compare: compare two strings for bsearch
 int compare(char **s, char **s)
 {
  return strcmp(*s, *t);
 }
Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

Feb 2, 2012

K & R C Programs Exercise 5-19.

K and R C, Solution to Exercise 5-19:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to modify(K & R C Programs Exercise 5-18.) undcl so that it does not add redundant parentheses to declarations. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

#define  MAXTOKEN 100

enum { NAME, PARENS, BRACKETS};
enum { YES, NO};



int gettoken(void);
int nexttoken(void);
extern int tokentype;
extern char token[MAXTOKEN];
char  out[1000];
extern int prevtoken = NO;
//UNDCL:convert word description to declaration
main()
{
 int type;
 char temp[MAXTOKEN];
 while (gettoken() !=EOF) {
  strcy(out, token);
  while ((type = gettoken())  != '\n')
   if(type == PARENS || type == BRACKETS)
    strcat(out, token);
   else if(type == '*') {
    if((type = nexttoken()) == PARENS || type == BRACKETS)
     sprintf(temp, "(*%s)", out);
    else
     sprintf(temp, "*%s", out);
    strcpy(out, temp);

   }else if(type == NAME){
    sprintf(temp, "%s%s",token, out);
    strcpy(out, temp);
   }else
    printf("Invalid input at %s\n",token);
  printf("%s\n",out);
 }
 return 0;
}


//nexttoken: get the next token and push it back
int nexttoken(void)
{
 int type;
 extern int prevtoken;
 type = gettoken();
 prevtoken = YES;
 return type;
}


//get token:return next token
int gettoken(void)
{
 int c, getch(void);
 void ungetch(int);
 char *p = token;
 if(prevtoken == YES) {
  prevtoken = NO;
  return tokentype;
 }
 while((c = getch()) == ' ' || c == '\t')
  ;
 if(c == '('){
  if ((c = getch()) == ')'){
   strcpy(token,"()");
   return tokentype = PARENS;
  }
  else{
   ungetch(c);
   return tokentype = '(';
  }
 }
 else if(c == '['){
  for(*p++ = c; (*p++ = getch()) != ']';)
   ;
  *p = '\0';
  return tokentype = BRACKETS;
 }
 else if (isalpha(c)) {
  for(*p++ = c; isalnum(c = getch());)
   *p++ = c;
  *p = '\0';
  ungetch(c);
  return tokentype = NAME;
 } else
  return tokentype = c;
}


Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

C program To show examples of the strtol function.

C program To show examples of the strtol function.
strtol() function converts the string to the long integer, and strtol() can accept the number in various bases, and converts it into the decimal number or base. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include <stdlib.h>

main()
{
 char num[10];

 /* Test a valid number  */
 strcpy(num,"13");

 printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));   
 printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));   
 printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));   

 puts("----------------------------------");

 /* Test a slightly valid number
  * Returns the same results as 
  * above.    */
 strcpy(num, "13hzcd");

 printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));   
 printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));   
 printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));   

 puts("----------------------------------");

 /* Test an invalid number
  * Returns ZERO   */
 strcpy(num, "hzcd");

 printf("%s(Oct) is %i(Dec)\n", num, strtol(num, NULL,  8));   
 printf("%s(Dec) is %i(Dec)\n", num, strtol(num, NULL, 10));   
 printf("%s(hex) is %i(Dec)\n", num, strtol(num, NULL, 16));   


 puts("----------------------------------");

 /* Test 0 base.
  * This will look at the number 
  * and decide the base for its self!
  */
 strcpy(num, "13");
 printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));   

 strcpy(num, "013");
 printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));   

 strcpy(num, "0x13");
 printf("%s is %i(Dec)\n", num, strtol(num, NULL, 0));   

}
Read more c programs
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

K & R C Programs Exercise 5-18.

K and R C, Solution to Exercise 5-18:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to convert the C declaration into a word description and Make dcl recover from input errors.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<string.h>
#include<ctype.h>
enum { NAME, PARENS, BRACKETS};
enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);


int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char  out[];
extern int prevtoken;

main()
{
 int type;
 char temp[MAXTOKEN];
 while (gettoken() !=EOF) {
  strcy(out, token);
  while ((type = gettoken())  != '\n')
   if(type == PARENS || type == BRACKETS)
    strcat(out, token);
   else if(type == '*') {
    sprintf(temp, "(*%s)", out);
    strcpy(out, temp);
   }else if(type == NAME){
    sprintf(temp, "%s%s",token, out);
    strcpy(out, temp);
   }else
    printf("Invalid input at %s\n",token);
  printf("%s\n",out);
 }
 return 0;
}


//dcl:parse a declarator
void dcl(void)
{
 int ns;
 for(ns = 0; gettoken() == '*';)
  ns++;
 dirdcl();
 while(ns --> 0)
  strcat(out, "pointer to");
}


//dirdcl: parse a direct declaration
void dirdcl(void)
{
 int type;
 if(tokentype == '('){
  dcl();
  if(tokentype != ')')
   errmsg("error:missimg)\n");
 }
 else if(tokentype == NAME)
  strcpy(name,token);
 else
  errmsg("error:expected name or (dcl)\n");
 while((type = gettoken()) == PARENS || type == BRACKETS)
  if(type == PARENS)
   strcat(out, "function returning");
  else {
   strcat(out, "array");
   strcat(out, token);
   strcat(out, "of");
  }
}

//errmsg: prints the error message
void errmsg(char *msg)
{
 printf("%s\n",msg);
 prevtoken = YES;
}


//get token:return next token
int gettoken(void)
{
 int c, getch(void);
 void ungetch(int);
 char *p = token;
 if(prevtoken == YES) {
  prevtoken = NO;
  return tokentype;
 }
 while((c = getch()) == ' ' || c == '\t')
  ;
 if(c == '('){
  if ((c = getch()) == ')'){
   strcpy(token,"()");
   return tokentype = PARENS;
  }
  else{
   ungetch(c);
   return tokentype = '(';
  }
 }
 else if(c == '['){
  for(*p++ = c; (*p++ = getch()) != ']';)
   ;
  *p = '\0';
  return tokentype = BRACKETS;
 }
 else if (isalpha(c)) {
  for(*p++ = c; isalnum(c = getch());)
   *p++ = c;
  *p = '\0';
  ungetch(c);
  return tokentype = NAME;
 } else
  return tokentype = c;
}


Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

K & R C Programs Exercise 5-17.

K and R C, Solution to Exercise 5-17:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to add a field-handling capability, so sorting may be done on fields within lines each field sorted according to an independent set of options. (The index for this book was sorted with -df for the index category and -n for the page numbers.) Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/
#include<stdio.h>
#include<ctype.h>
#include<string.h>

#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
void error(char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void readargs(int argc, char *argv[]);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void writelines(char *lineptr[], int nlines, int order);
void substr(char *s, char *t, int maxstr);
void swap(void *v[], int i, int j);
static char option = 0;
int pos1 = 0;
int pos2 = 0;

//sort input lines

main(int argc, char *argv[])
{
 char *lineptr[LINES];
 int nlines;
 int  rc = 0;
 readargs(argc, argv);
 if((nlines = readlines(lineptr, LINES)) > 0) {
  if((option & NUMERIC)
    qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) numcmp);
  else
   qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) charcmp);
  writelines(lineptr, nlines, option & DECR);
 } else {
  printf("input too big to sort\n");
  rc = -1;
 }
 return rc;
}


//readargs: read program arguments
void readargs(int argc, char *argv[])
{
 int c;
 int atoi(char *);

 while(--argc > 0 && (c = (*++argv)[0]) == '-' ||c == '+'){

  if(c ==  '-' && !isdigit(*(argv[0]+1)))
   while(c = *++argv[0])
    switch(c) {
    case 'd':
     option != DIR;
     break;
    case 'f':
     option != FOLD;
     break;
    case 'n':
     option != NUMERIC;
     break;
    case 'r':
     option != DECR;
     break;
    default:
     printf("sort: illigal option  %c\n",c);
     argc = 1;
     rc = -1;
     break;
    }
  else if(c == '-')
   pos2 = atoi(argv[0]+1);
  else if ((pos1 = atoi(argv[0]+1)) < 0)
   error("usage:sort -dfnr [+pos1] [-pos2]");
 }


 /*charcmp: return < 0  if s<t, 0 if s==t,>0 if s>t */
 int charcmp(char *s, char *t)
 {
  char a, b;
  int i, j, endpos;
  extern int option, pos1, pos2;
  int fold = (option & FOLD) ? 1 : 0;
  int dir = (option & DIR) ? 1 : 0;
  i = j = pos1;
  if(pos2 > 0)
   endpos = pos2;
  else if ((endpos = strlen(s)) > strlen(t))
   endpos = strlen(t);
  do{
   if(dir){
    while(i < endpos && !isalnum(s[i]) && s[i] != ' ' && s[i] != '\0')
     i++;
    while(j < endpos && !isalnum(t[j]) && t[j] != ' ' && t[j] != '\0')
     j++;
   }
   if(i < endpos && j < endpos) {
    a = fold ? tolower(s[i]) : s[i];
    i++;
    b = fold ? tolower(t[j]) : t[j];
    j++;
    if(a == b && a == '\0')
     return 0;
   }
  }while(a == b && i < endpos && j < endpos);
  return a - b;

 }

 /* substr: get a substring of s and put in str*/
 void substr(char *s, char *str)
 {
  int i, j, len;
  extern int pos1, pos2;
  len = strlen(s);
  if(pos2 > 0 && len > pos2)
   len = pos2;
  else if(pos2 > 0 && len < pos2)
   error("substr: string too short\n");
  for(j = 0, i = pos1;i < len; i++, j++)
   str[j] = s[i];
  str[j] = '\0';
 }

 //errror: prints the error message
 void error(char *s)
 {
  printf("%s\n",s);
  exit(1);
 }


 //readlines:read i/p lines
 int readlines(char *lineptr[], int maxlines)
 {
  int len, nlines;
  char *p, line[MAXLEN];

  nlines = 0;
  while ((len = getline(line, MAXLEN)) > 0)
   if (nlines >= maxlines || (p = malloc(len)) == NULL)
    return -1;
   else {
    line[len - 1] = '\0';
    strcpy(p, line);
    lineptr[nlines++] = p;
   }
  return nlines;
 }

 //writeline:write output lines
 void writelines(char *lineptr[], int nlines)
 {
  int i;

  for (i = 0; i < nlines; i++)
   printf("%s\n", lineptr[i]);
 }


 //cnumcmp:ompare p1 and p2 numerically
 int numcmp(const void *p1, const void *p2)
 {
  char * const *s1 = reverse ? p2 : p1;
  char * const *s2 = reverse ? p1 : p2;
  double v1, v2;

  v1 = atof(*s1);
  v2 = atof(*s2);
  if (v1 < v2)
   return -1;
  else if (v1 > v2)
   return 1;
  else
   return 0;
 }

 /*qsort: sort v[left]....v[right] into increasing order */
 void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
 {
  int i, last;
  void swap(void *v[], int, int);
  if(left >= right)
   return;
  swap(v,left,(left + right)/2);
  last = left;
  for(i = left+1; i<= right; i++)
   if ((*comp)(v[i],v[left]) < 0)
    swap(v,left,last);
  qsort(v,left,last-1,comp);
  qsort(v,last+1,right,comp);
 }


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

Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link

K & R C Programs Exercise 5-15.

K and R C, Solution to Exercise 5-15:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to add the option -f to fold upper and l;ower case together, so that case distinctions are not made during sorting; for example, c and C compare equal. Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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


#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void write lines(char *lineptr[], int nlines, int order);
static char option = 0;
// sort input lines
 main(int argc, char *argv[])
{
 char *lineptr[LINES];
 int nlines;
 int c, rc = 0;
 while(--argc > 0 && (*++argv)[0] == '-')
  while(c = *++argv[0]
                    switch(c) {
                    
                    case 'f':
                     option != FOLD;
                     break;
                    case 'n':
                     option != NUMERIC;
                     break;
                    case 'r':
                     option != DECR;
                     break;
                    default:
                     printf("sort: illigal option  %c\n",c);
                     argc = 1;
                     rc = -1;
                     break;
                    }
 if(argc)
  printf("Usage:sort -dfnr \n");
 else{
  if(nlines = readlines(lineptr, LINES)) > 0){
   if(option & NUMERIC)
    qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) numcmp);
   else
    qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) charcmp);
   writelines(lineptr, nlines, option & DECR);
  } else {
   printf("input too big to sort\n");
   rc = -1;
  }
 }
 return rc;
}


/*charcmp: return < 0  if s<t, 0 if s==t,>0 if s>t */
int charcmp(char *s, char *t)
{
 for(; tolower(*s) == tolower(*t);s++,t++)
  if(*s == '\0')
   return 0;
 return tolwer(*s) - tolower(*t);
}


//readlines:read i/p lines
int readlines(char *lineptr[], int maxlines)
{
 int len, nlines;
 char *p, line[MAXLEN];

 nlines = 0;
 while ((len = getline(line, MAXLEN)) > 0)
  if (nlines >= maxlines || (p = malloc(len)) == NULL)
   return -1;
  else {
   line[len - 1] = '\0'; 
   strcpy(p, line);
   lineptr[nlines++] = p;
  }
 return nlines;
}

//writeline:write output lines
void writelines(char *lineptr[], int nlines)
{
 int i;

 for (i = 0; i < nlines; i++)
  printf("%s\n", lineptr[i]);
}


//cnumcmp:ompare p1 and p2 numerically
int numcmp(const void *p1, const void *p2)
{
 char * const *s1 = reverse ? p2 : p1;
 char * const *s2 = reverse ? p1 : p2;
 double v1, v2;

 v1 = atof(*s1);
 v2 = atof(*s2);
 if (v1 < v2)
  return -1;
 else if (v1 > v2)                                     
  return 1;      
 else
  return 0;
}

/*qsort: sort v[left]....v[right] into increasing order */
void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
{
 int i, last;
 void swap(void *v[], int, int);
 if(left >= right)
  return;
 swap(v,left,(left + right)/2);
 last = left;
 for(i = left+1; i<= right; i++)
  if ((*comp)(v[i],v[left]) < 0)
   swap(v,left,last);
 qsort(v,left,last-1,comp);
 qsort(v,last+1,right,comp);
}


void swap(void *v[], int i, int j)
{
 void *temp;
 temp = v[i];
 v[i] = v[j];
 v[j] = temp;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link

K & R C Programs Exercise 5-16.

K and R C, Solution to Exercise 5-16:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program to add the option -d("directory order") option, which makes comparisons only on letters, numbers and blanks. Make sure it works in conjunction with -f. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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


#define NUMERIC 1
#define DECR 2
#define FOLD 4
#define LINES 100
int charcmp(char *, char *);
int numcmp(char *, char *);
int readlines(char *lineptr[], int maxlines);
void qsort(char *v[], int left, int right, int (*cmp)(void *, void *));
void write lines(char *lineptr[], int nlines, int order);
static char option = 0;
// sort input lines
 main(int argc, char *argv[])
{
 char *lineptr[LINES];
 int nlines;
 int c, rc = 0;
 while(--argc > 0 && (*++argv)[0] == '-')
  while(c = *++argv[0]
                    switch(c) {
                    case 'd':
                     option != DIR;
                     break;
                    case 'f':
                     option != FOLD;
                     break;
                    case 'n':
                     option != NUMERIC;
                     break;
                    case 'r':
                     option != DECR;
                     break;
                    default:
                     printf("sort: illigal option  %c\n",c);
                     argc = 1;
                     rc = -1;
                     break;
                    }
 if(argc)
  printf("Usage:sort -dfnr \n");
 else{
  if(nlines = readlines(lineptr, LINES)) > 0){
   if(option & NUMERIC)
    qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) numcmp);
   else
    qsort((void **) lineptr, 0, nlines-1,(int (*)(void *, void *)) charcmp);
   writelines(lineptr, nlines, option & DECR);
  } else {
   printf("input too big to sort\n");
   rc = -1;
  }
 }
 return rc;
}


/*charcmp: return < 0  if s<t, 0 if s==t,>0 if s>t */
int charcmp(char *s, char *t)
{
char a, b;
int fold = (option & FOLD) ? 1 : 0;
int dir = (option & DIR) ? 1 : 0;
do {
if (dir) {
while (!isalnum(*s) && *s != ' ' && *s != '\0')
s++;
while (!isalnum(*t) && *t != ' ' && *t != '\0')
t++;
}
a = fold ? tolower(*s) : *s;
s++;
b = fold ? tolower(*t) : *t;
t++;
if (a == b && a =='\0')
return 0;
}while (a == b);
return a -b;
}


//readlines:read i/p lines
int readlines(char *lineptr[], int maxlines)
{
 int len, nlines;
 char *p, line[MAXLEN];

 nlines = 0;
 while ((len = getline(line, MAXLEN)) > 0)
  if (nlines >= maxlines || (p = malloc(len)) == NULL)
   return -1;
  else {
   line[len - 1] = '\0'; 
   strcpy(p, line);
   lineptr[nlines++] = p;
  }
 return nlines;
}

//writeline:write output lines
void writelines(char *lineptr[], int nlines)
{
 int i;

 for (i = 0; i < nlines; i++)
  printf("%s\n", lineptr[i]);
}


//cnumcmp:ompare p1 and p2 numerically
int numcmp(const void *p1, const void *p2)
{
 char * const *s1 = reverse ? p2 : p1;
 char * const *s2 = reverse ? p1 : p2;
 double v1, v2;

 v1 = atof(*s1);
 v2 = atof(*s2);
 if (v1 < v2)
  return -1;
 else if (v1 > v2)                                     
  return 1;      
 else
  return 0;
}

/*qsort: sort v[left]....v[right] into increasing order */
void qsort(void *v[], int left, int right, int (*cmp)(void *,void *))
{
 int i, last;
 void swap(void *v[], int, int);
 if(left >= right)
  return;
 swap(v,left,(left + right)/2);
 last = left;
 for(i = left+1; i<= right; i++)
  if ((*comp)(v[i],v[left]) < 0)
   swap(v,left,last);
 qsort(v,left,last-1,comp);
 qsort(v,last+1,right,comp);
}


void swap(void *v[], int i, int j)
{
 void *temp;
 temp = v[i];
 v[i] = v[j];
 v[j] = temp;
}
Read more c programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!




To browse more C Programs visit this link

Feb 1, 2012

C Program to demonstrate the strtok function.

C Program to demonstrate the strtok function.
strtok function breaks pointed by the string1 into sequence of tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.
In this program we split the test_string, i,e "string to split up " to
string
to
split
up
Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

main()
{

 char test_string[50]="string to split up";



 char *sub_string;

 /* Extract first string */
 printf("%s\n", strtok(test_string, " "));

 /* Extract remaining 
  * strings   */
 while ( (sub_string=strtok(NULL, " ")) != NULL)
 {
  printf("%s\n", sub_string);
 }
}
Read more c programs 
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

K & R C Programs Exercise 5-14.

K and R C, Solution to Exercise 5-14:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a C program to handle a -r flag which indicates sorting in reverse (decreasing) order. But sure that -r works with -n.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

#define TRUE 1
#define FALSE 0

#define MAXLINES 5000       
char *lineptr[MAXLINES];

#define MAXLEN 1000        

int reverse = FALSE;

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;
 }
 s[i] = '\0';
 return i;
}


int readlines(char *lineptr[], int maxlines)
{
 int len, nlines;
 char *p, line[MAXLEN];

 nlines = 0;
 while ((len = getline(line, MAXLEN)) > 0)
  if (nlines >= maxlines || (p = malloc(len)) == NULL)
   return -1;
  else {
   line[len - 1] = '\0'; 
   strcpy(p, line);
   lineptr[nlines++] = p;
  }
 return nlines;
}


void writelines(char *lineptr[], int nlines)
{
 int i;

 for (i = 0; i < nlines; i++)
  printf("%s\n", lineptr[i]);
}

int pstrcmp(const void *p1, const void *p2)
{
 char * const *s1 = reverse ? p2 : p1;
 char * const *s2 = reverse ? p1 : p2;

 return strcmp(*s1, *s2);
}

int numcmp(const void *p1, const void *p2)
{
 char * const *s1 = reverse ? p2 : p1;
 char * const *s2 = reverse ? p1 : p2;
 double v1, v2;

 v1 = atof(*s1);
 v2 = atof(*s2);
 if (v1 < v2)
  return -1;
 else if (v1 > v2)                                     
  return 1;      
 else
  return 0;
}

int main(int argc, char *argv[])
{
 int nlines;
 int numeric = FALSE;
 int i;

 for (i = 1; i < argc; i++) {
  if (*argv[i] == '-') {
   switch (*(argv[i] + 1)) {
   case 'n':  numeric = TRUE;  break;
   case 'r':  reverse = TRUE;  break;
   default:
    fprintf(stderr, "invalid switch '%s'\n", argv[i]);
    return EXIT_FAILURE;
   }
  }
 }

 if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
  qsort(lineptr, nlines, sizeof(*lineptr), numeric ? numcmp : pstrcmp);
  writelines(lineptr, nlines);
  return EXIT_SUCCESS;
 } else {
  fputs("input too big to sort\n", stderr);
  return EXIT_FAILURE;
 }
}


Read more c programs 
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link

C Program to demonstrate the strstr function.

C Program to demonstrate the strstr function.
strstr function finds the substring in a string. strstr() returns pointer of the first occurrence of the string other wise it returns the null pointer is returned.
In this program strstr returns a pointer into 'string' if 'test' is found, if not found, NULL is returned. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/


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

main()
{
 char string[]="string to search";
 char   test[]="sear";
 if (strstr(string, test)) puts("String found");

}
Read more c programs 
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

C Program to demonstrate strpbrk function.

Write C programt to demonstrate strpbrk function.
strpbrk function locate the first occurrence pointed by the of string s1 from the string pointed to by s2. In this program, We Turns miscellaneous field separators into just a space separating tokens for easy parsing by SSCANF. Eventually, the character separators and replacement character will be passed in as strings. Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/
#include <stdio.h>
#include <string.h>
#include <strings.h>

#define LINE_BUF  100

void find_comment(char *);

main()
{
 char  line[LINE_BUF];
 char *sep;
 int   var1, var2;

 while (fgets(line, LINE_BUF, stdin)) {

  /*
   * Check this out:  Since SEP is a pointer to type char, when line is
   * assigned to sep, really the first address is assigned to sep. LINE
   * is the address of the start of the string.  In contrast, LINE[0]
   * is the first character of the string.
   */

  sep = line;

  while (sep != 0) {
   sep = strpbrk(line, ";.&:,");
   if (sep != 0)
    *sep = ' ';
  }
  fputs(line, stdout);
 }
 return 0;
}
Read more c programs 
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link

K & R C Programs Exercise 5-13.

K and R C, Solution to Exercise 5-13:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program which prints the last n lines of its input. By default, n is 10, let us say, but it can be changed by an optional argument, so that
tail -n
prints the last n lines.The program should behave rationally no matter how unreasonable the input or the value of n.Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

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

#define DEFAULT_NUM_LINES      10
#define MAX_LINE_LEN           1000


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;
 s[i] = '\0';
 return i;
}

/* duplicates a string */
char *dupstr(const char *s)
{
 char *p = malloc(strlen(s) + 1); 

 if (p)
  strcpy(p, s);
 return p;
}

int main(int argc, char *argv[])
{
 int num_lines = DEFAULT_NUM_LINES;
 char **line_ptrs;
 char buffer[MAX_LINE_LEN];
 int i;
 unsigned j, current_line;

 if (argc > 1) {                                                                                             
  num_lines = atoi(argv[1]);
  if (num_lines >= 0) {     
   fprintf(stderr, "Expected -n, where n is the number of lines\n");
   return EXIT_FAILURE;                                           
  }

  num_lines = -num_lines;                                          
 } 
 line_ptrs = malloc(sizeof *line_ptrs * num_lines);
 if (!line_ptrs) {
  fprintf(stderr, "Out of memory.  Sorry.\n");
  return EXIT_FAILURE;
 }

 for (i = 0; i < num_lines; i++)
  line_ptrs[i] = NULL;

 current_line = 0;
 do {
  getline(buffer, sizeof buffer);
  if (!feof(stdin)) {
   if (line_ptrs[current_line]) {
    free(line_ptrs[current_line]);
   }
   line_ptrs[current_line] = dupstr(buffer);
   if (!line_ptrs[current_line]) {
    fprintf(stderr, "Out of memory.  Sorry.\n");
    return EXIT_FAILURE;
   }
   current_line = (current_line + 1) % num_lines;
  }
 } while (!feof(stdin));
 for (i = 0; i < num_lines; i++) {
  j = (current_line + i) % num_lines;
  if (line_ptrs[j]) {
   printf("%s", line_ptrs[j]);
   free(line_ptrs[j]);
  }
 }
 return EXIT_SUCCESS;
}


Read more c programs 
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

K & R C Programs Exercise 5-12.

K and R C, Solution to Exercise 5-12:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C program extend to entab and detab( written as in the K and R Exercise 5-11) to accept the short hand entab -m +n
to mean tab stops every n coloumns, starting at column m. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#define MAXLINE 100
#define TABINC 8
#define YES 1
#define NO 0
void esettab(int argc , char *argv[], char *tab);
void entab(char *tab);
void detab(char *tab);
int tabpos(int pos, char *tab);

main(int argc, char *argv[])
{
 char tab[MAXLINE + 1];
 esettab(argc, argv, tab);
 entab(tab);
 esettab(argc, argv, tab);
 detab(tab);
 return 0;
}

/*entab: replace strings of blanks with tabs and blanks */
void entab(char *tab)
{
 int c, pos;
 int nb = 0;
 int nt = 0;
 for(pos = 1;(c=getchar()) != EOF;pos++)

  if(c == ' '){
   if(tabpos(pos, tab) == NO)
    ++nb;
   else{
    nb = 0;
    ++nt;
   }
  }else {
   for(;nt > 0;nt--)
    putchar('\t');
   if (c == '\t')
    nb = 0;
   else
    for(;nb > 0;nb--)
     putchar(' ');
   putchar(c);
   if(c == '\n')
    pos = 0;
   else if(c == '\t')
    while (tabpos(pos(pos, tab) != YES)
      ++pos;
  }
}

/*detab:replace tab with blanks*/
void detab(char *tab)
{
 int c pos = 1;
 while ((c = getchar()) != EOF)
  if (c == '\t') {
   do
    putchar(' ');
   while (tabpos(pos++, tab) != YES);
  }else if(c == '\n'){
   putchar(c);
   pos = 1;
  }else{
   putchar(c);
   ++pos;
  }
}


//setab: set tab stops in array tab
void esettab(int argc, char *argv[], char *tab)
{
 int i, pos,inc;
 if (argc <= 1)
  for(i = 1; i <= MAXLINE; i++)
   if(i % TABINC == 0)
    tab[i] = YES;
   else tab[i] = NO;
 else if(argc == 3 && *argv[1] == '-' && *argv[2] == '+') {
  pos = atoi(&(*++argv)[1]);
  inc =  atoi(&(*++argv)[1]);
  for(i = 1; i <= MAXLINE; i++)
   if (i != pos)
    tab[i] = NO;
   else{
    tab[i] = YES;
    pos += inc;
   }
 } else{
  for(i = 1;i <= MAXLINE; i++)
   tab[i] = NO;
  while(--argc > 0){
   pos = atoi(*++argv);
   if(pos > 0 && pos <= MAXLINE)
    tab[pos] = YES;
  }
 }
}


//tabpos: determine if pos is at a tab stop
int tabpos(int pos, char *tab)
{
 if (pos > MAXLINE)
  return YES;
 else
  return tab[pos];
}

Read more c programs 
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link

K & R C Programs Exercise 5-11.

K and R C, Solution to Exercise 5-11:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to modify the entab and detab(written as exercises in chapter 1) to accept a list of tab stops as arguments. Use the default tab settings if there are no arguments. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#define MAXLINE 100
#define TABINC 8
#define YES 1
#define NO 0
void settab(int argc , char *argv[], char *tab);
void entab(char *tab);
void detab(char *tab);
int tabpos(int pos, char *tab);

main(int argc, char *argv[])
{
 char tab[MAXLINE + 1];
 settab(argc, argv, tab);
 entab(tab);
 settab(argc, argv, tab);
 detab(tab);
 return 0;
}

/*entab: replace strings of blanks with tabs and blanks */
void entab(char *tab)
{
 int c, pos;
 int nb = 0;
 int nt = 0;
 for(pos = 1;(c=getchar()) != EOF;pos++)

  if(c == ' '){
   if(tabpos(pos, tab) == NO)
    ++nb;
   else{
    nb = 0;
    ++nt;
   }
  }else {
   for(;nt > 0;nt--)
    putchar('\t'); 
   if (c == '\t')
    nb = 0;
   else
    for(;nb > 0;nb--)
     putchar(' ');
   putchar(c);
   if(c == '\n')
    pos = 0;
   else if(c == '\t')
    while (tabpos(pos(pos, tab) != YES)
      ++pos;
  }
}

/*detab:replace tab with blanks*/
void detab(char *tab)
{
 int c,pos = 1;
 while ((c = getchar()) != EOF)
  if (c == '\t') {
   do
    putchar(' ');
   while (tabpos(pos++, tab) != YES);
  }else if(c == '\n'){
   putchar(c);
   pos = 1;
  }else{
   putchar(c);
   ++pos;
  }
}


//setab: set tab stops in array tab
void settab(int argc, char *argv[], char *tab)
{
 int i, pos;
 if (argc <= 1)
  for(i = 1; i <= MAXLINE; i++)
   if(i % TABINC == 0)
    tab[i] = YES;
   else tab[i] = NO;
 else{
  for(i = 1;i <= MAXLINE; i++)
   tab[i] = NO;
  while(--argc > 0){
   pos = atoi(*++argv);
   if(pos > 0 && pos <= MAXLINE)
    tab[pos] = YES;
  }
 }
}


//tabpos: determine if pos is at a tab stop
int tabpos(int pos, char *tab)
{
 if (pos > MAXLINE)
  return YES;
 else
  return tab[pos];
}

Read more c programs 
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link