C Aptitude Questions and answers with explanation

C Aptitude 29
C program is one of most popular programming language which is used for core level of coding across the board. C program is used for operating systems, embedded systems, system engineering, word processors,hard ware drivers, etc.

In this site, we have discussed various type of C programs till date and from now on, we will move further by looking at the C aptitude questions.

In the coming days, we will post C aptitude questions, answers and explanation for interview preparations.

The C aptitude questions and answers for those questions along with explanation for the interview related queries.

We hope that this questions and answers series on C program will help students and freshers who are looking for a job, and also programmers who are looking to update their aptitude on C program.
Some of the illustrated examples will be from the various companies, and IT industry experts.
Read more about C Programming Language . and read the C Programming Language (2nd Edition). by K and R.

Predict the output or error(s) for the following:

C aptitude 29.1

  enum colors {BLACK,BLUE,GREEN}
main()
{

printf("%d..%d..%d",BLACK,BLUE,GREEN);

return(1);
}

Answer: 0..1..2

Explanation: enum assigns numbers starting from 0, if not explicitly defined.

C aptitude 29.2

   void main()
{
char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

}


Answer: 4..2

Explanation: The second pointer is of char type and not a far pointer

C aptitude 29.3

     main()
{
int i=400,j=300;
printf("%d..%d");
}

Answer: 400..300

Explanation: printf takes the values of the first two assignments of the program. Any number of printf’s may be given. All of them take only the first two.

Read more Similar C Programs 
Learn C Programming
C Aptitude
C Interview questions
 

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

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) www.c-program-example.com

K & R C Chapter 5 Exercise Solutions.

We have already provided solutions to all the exercises in the bookC Programming Language (2nd Edition) popularly known as K & R C book.

In this blog post I will give links to all the exercises from Chapter 5 of the book for easy reference.

Chapter 5: Pointers and Arrays

  1. Exercise 5-1. As written, getint treats a + or – not followed by a digit as a valid representation of zero. Fix it to push such a character back on the input.
    Solution to Exercise 5-1.
  2. Exercise 5-2.Write getfloat , the floating-point analog of getint . What type does getfloat return as its function value?
    Solution to Exercise 5-2.
  3. Exercise 5-3.GWrite a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s .
    Solution to Exercise 5-3.
  4. Exercise 5-4. Write the function strend(s,t) , which returns 1 if the string t occurs at the end of the string s , and zero otherwise.
    Solution to Exercise 5-4.
  5. Exercise 5-5. Write versions of the library functions strncpy , strncat , and strncmp , which operate on at most the first n characters of their argument strings. For example, strncpy(s,t,n) copies at most n characters of t to s . Full descriptions are in Appendix B.
    Solution to Exercise 5-5.
  6. Exercise 5-6. Rewrite appropriate programs from earlier chapters and exercises with pointers instead of array indexing. Good possibilities include getline (Chapters 1 and 4), atoi , itoa , and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and getop (Chapter 4).
    Solution to Exercise 5-6.
  7. Exercise 5-7. Rewrite readlines to store lines in an array supplied by main , rather than calling alloc to maintain storage. How much faster is the program?
    Solution to Exercise 5-7.
  8. Exercise 5-8.There is no error-checking in day_of_year or month_day. Remedy this defect.
    Solution to Exercise 5-8.
  9. Exercise 5-9.Rewrite the routines day_of_year and month_day with pointers instead of indexing.
    Solution to Exercise 5-9.
  10. Exercise 5-10. Write the program expr , which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument. For example, expr 2 3 4 + * evaluates 2 X (3+4).
    Solution to Exercise 5-10.
  11. Exercise 5-11. Modify the programs 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.
    Solution to Exercise 5-11.
  12. Exercise 5-12. Extend entab and detab to accept the shorthand entab -m +n to mean tab stops every n columns, starting at column m . Choose convenient (for the user) default behavior.
    Solution to Exercise 5-12.
  13. Exercise 5-13. Write the program tail, which prints the last n lines of its input. By default, n is 10, 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. Write the program so it makes the best use of available storage; lines should be stored as in the sorting program of Section 5.6, not in a two-dimensional array of fixed size.
    Solution to Exercise 5-13.
  14. Exercise 5-14. Modify the sort program to handle a -r flag, which indicates sorting in reverse (decreasing) order. Be sure that -r works with -n.
    Solution to Exercise 5-14.
  15. Exercise 5-15.Add the option -f to fold upper and lower case together, so that case distinctions are not made during sorting; for example, a and A compare equal.
    Solution to Exercise 5-15.
  16. Exercise 5-16.Add the -d (“directory order”) option, which makes comparisons only on letters, numbers and blanks. Make sure it works in conjunction with -f .
    Solution to Exercise 5-16.
  17. Exercise 5-17. 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.)
    Solution to Exercise 5-10.
  18. Exercise 5-18. Make dcl recover from input errors.
    Solution to Exercise 5-18.
  19. Exercise 5-19. Modify undcl so that it does not add redundant parentheses to declarations.
    Solution to Exercise 5-19.
  20. Exercise 5-20. Expand dcl to handle declarations with function argument types, qualifiers like const , and so on.
    Solution to Exercise 5-20.
You can purchase the book from here or here.

To get regular updates on new C programs, you can Follow @c_program

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

our page!

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

To browse more C Programs visit this link
(c) www.c-program-example.com

K & R C Programs Exercise 7-4.

K and R C, Solution to Exercise 7-4:
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 private version of scanf analogous to minprintf from the previous section.
minscanf is similar to minprintf. This function collects characters from the format string until it finds an alphabetic character after a %. That is the localfmt passsed to scanf along with the appropriate pointer.
The arguments to scanf are pointers: a pointer to a format string and a pointer to the variable that receives the value from scanf.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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#define LOCALFMT 100

/* minscanf: minimal scanf with variable argument list */
void minscanf(char *fmt, ...)
{
va_list ap;
char *p, *sval;
char localfmt[LOCALFMT];
int i,c;
int *ival;
double *dval;
unsigned *uval;

va_start(ap, fmt); /* make ap point to the first unnamed arg */
for (p = fmt; *p; p++) {
if (*p != '%') {
localfmt[i++] = *p;
continue;
}
i = 0;
localfmt[i++] = '%';
while(*p(p+1) && !isalpha(*(p+1)))
localfmt[i++] = *++p;
localfmt[i++] = *(p+1);
localfmt[i] = '/0';
switch (*++p) {
case 'd':
case 'i':
ival = va_arg(ap, int *);
scanf(localfmt, ival);
break;

case 'u':

case 'o':

case 'x':

case 'X':


case 'f':
dval = va_arg(ap, double);
scanf(localfmt, dval);
break;

case 's':
sval = va_arg(ap, char *);
scanf(localfmt, sval);
break;
default:
scanf(localfmt);
break;
}
i = 0;
}
va_end(ap);
}


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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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] == '')
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("%sn",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 = '';
return tokentype = BRACKETS;
}
else if (isalpha(c)) {
for(*p++ = c; isalnum(c = getch());)
*p++ = c;
*p = '';
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 declarationn");
}

//dclspec: declaration specification
void dclspec(void)
{
char temp[MAXTOKEN];
temp[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 listn");
}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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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 sortn");
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 %cn",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] != '')
i++;
while(j < endpos && !isalnum(t[j]) && t[j] != ' ' && t[j] != '')
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 == '')
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 shortn");
for(j = 0, i = pos1;i < len; i++, j++)
str[j] = s[i];
str[j] = '';
}

//errror: prints the error message
void error(char *s)
{
printf("%sn",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] = '';
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("%sn", 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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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 %cn",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 sortn");
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 == '')
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] = '';
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("%sn", 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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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] = '';
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 linesn");
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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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 Follow @c_program

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) www.c-program-example.com

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 [email protected]
* 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 Follow @c_program

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) www.c-program-example.com

K & R C Programs Exercise 5-9.

K and R C, Solution to Exercise 5-9:
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 , Rewrite the routines of K & R C Programs Exercise 5-8 day_of_year and month_day with pointers instead of indexing.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 [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>

static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};



int day_of_year(int year, int month, int day)
{
int i, leap;
char *p;

leap = (year%4 == 0 && year%100 != 0) || year%400 == 0;

/* Set `p' to point at first month in the correct row. */
p = &daytab[leap][1];

/* Move `p' along the row, to each successive month. */
for (i = 1; i < month; i++) {
day += *p;
++p;
}
return day;
}

void month_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;
char *p;

leap = (year%4 == 0 && year%100 != 0) || year%400 == 0;
p = &daytab[leap][1];
for (i = 1; yearday > *p; i++) {
yearday -= *p;
++p;
}
*pmonth = i;
*pday = yearday;
}


int main(void)
{
int year, month, day, yearday;

year = 2012;
month = 7;
day = 9;
printf("The date is: %d-%02d-%02dn", year, month, day);
printf("day_of_year: %dn", day_of_year(year, month, day));



yearday = 61; /* 2012-03-01 */
printf("Yearday is %dn", yearday);
month_day(year, yearday, &month, &day);
printf("month_day_pointer: %d %dn", month, day);

return 0;
}


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 Follow @c_program

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) www.c-program-example.com