K & R C Programs Exercise 7-7.

K and R C, Solution to Exercise 7-7:
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 pattern-finding program of chapter 5(C Programming Language  2nd Edition, page no 117.) to take its input from a set of named files or, if no files are named as arguments, from the standard input. Should the file name be printed when a matching line is found.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<stdlib.h>

#define MAXLINE 1000

/*print lines that match pattern from 1st argument */
main(int argc, char *argv[])
{
char pattern[MAXLINE];
int c, excpet = 0,number = 0;
FILE *fp;
void fpat(FILE *fp, char *fname, char *pattern, int except, int number);

while(--argc > 0 && (*++argv)[0] == '-')
while(c = *++argv[0])
switch(c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
printf("find:illigal option %cn",c);
argc = 0;
break;
}
if(argc >= 1)
strcpy(pattern, *argv);
else{
printf("Usage:find[-x] [-n] pattern [file....]n");
exit(1);
}
if(argc == 1)
fpat(stdin,"",pattern,except,number);
else
while(--argc > 0)
if((fp = fopen(*++argv,"r")) == NULL) {
fprintf(stderr,"find:can't open %sn",*argv);
exit(1);
} else {
fpat(fp, *argv, pattern,except,number);
fclose(fp);}
return 0;
}

/*fpat: find pattern*/
void fpat(FILE *fp, char *fname, char *pattern, int except, int number)
{
char line[MAXLINE];
long loneno = 0;

while(fgets(line, MAXLINE, fp) != NULL){
++lineno;
if((strstr(line,pattern) != NULL) !=except) {
if(*fname)
printf("%s -",fname);
if(number)
printf("%ld: ",lineno);
printf("%s",line);
}
}
}



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 7-5.

K and R C, Solution to Exercise 7-5:
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.
Rewrite the postfix calculator of chapter 4 to use scanf and/or sscanf to do the input number conversion.
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<math.h> /*for atof()*/
#define MAXTOP 100 /* max size of operand or operator */
#define NUMBER '0' /* SIGNAL THAT A NUMBER WAS FOUND */
#define MAXVAL 100
int gettop(char []);
void push(double);
double pop(void);
int sp = 0; /* Next free stack position. */
double val[MAXVAL];


//reverse Polish calulator
int main(void)
{
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 '*':
push(pop() * pop());
break;

case '-':
op2=pop();
push(pop() - op2);
break;
case '-':
op2=pop();
if(op2 != 0.0)
push(pop() / op2);
else printf("nError: Zero divissorn");
break;
case '%':
op2 = pop();
if(op2)
push(fmod(pop(), op2));
else
printf("nError: Division by zero!");
break;
case 'n':
printf("t%.8gn",pop());
break;
default:
printf("error: unknown command %sn", s);
break;

}
}
return 0;
}




/* Getop: get next operator or numeric operand. */
int getop(char s[])
{

int i = 0;
int c;
int rc;
static char lastc[] = " ";
sscanf(lastc,"%c", &c);
lastc[0] = ' ';

/* Skip whitespace */
while((s[0] = c ) == ' ' || c == 't')
if(scanf("%",&c) == EOF)
c = EOF;
s[1] = '';

/* Not a number but may contain a unary minus. */
if(!isdigit(c) && c != '.' )
return c;


if(isdigit(c))
do{
rc = scanf("%c",&c);
if(!isdigit(s[++i] = c))
break;
}while(rc != EOF)

if(c == '.')
do{
rc = scanf("%c",&c);
if(!isdigit(s[++i] = c))
break;
}while(rc != EOF)

s[i] = '';
if(rc != EOF)
lastc[0] = c;
return NUMBER;

}



/* push: push f onto stack. */
void push(double f)
{
if(sp < MAXVAL)
val[sp++] = f;
else
printf("nError: stack full can't push %gn", f);
}

/*pop: pop and return top value from stack.*/
double pop(void)
{
if(sp > 0)
return val[--sp];
else
{
printf("nError: stack emptyn");
return 0.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

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 [email protected]
* 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("%dtt%d",i,j);
printf("n");
sum = sum + j;
}
}
printf("nnSum 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 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

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 [email protected]
* 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 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-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 [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 '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;
}
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)
{
char a, b;
int fold = (option & FOLD) ? 1 : 0;
int dir = (option & DIR) ? 1 : 0;
do {
if (dir) {
while (!isalnum(*s) && *s != ' ' && *s != '')
s++;
while (!isalnum(*t) && *t != ' ' && *t != '')
t++;
}
a = fold ? tolower(*s) : *s;
s++;
b = fold ? tolower(*t) : *t;
t++;
if (a == b && a =='')
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] = '';
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

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 [email protected]
* 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("%sn", strtok(test_string, " "));

/* Extract remaining
* strings */
while ( (sub_string=strtok(NULL, " ")) != NULL)
{
printf("%sn", 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 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

C Program to demonstrate sscanf statement.

C Program to demonstrate the ‘sscanf’ statement.
sscanf statement reads formatted data from the string, Different syntax of sscanf are:
A = sscanf(str, format)
A = sscanf(str, format, sizeA)
[A, count] = sscanf(…)
[A, count, errmsg] = sscanf(…)
[A, count, errmsg, nextindex] = sscanf(…).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>

main()
{
char Host[64];
char User[64];
char *Buff = "Jobname=job1 Hostname=arnamul User=leslim Time=11:15";
/* <----------> <-----> <---------> <-------->
* | | | |
* | ------------ | |
* | | ------------------ V
* | | | NULL
* V V V */
sscanf (Buff, "%*s Hostname=%s %s", Host, User);

printf("Host is %sn", Host);
printf("User is %sn", User);
exit(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

C Program to demonstrate sprintf statement.

C Program to demonstrate the ‘sprintf‘ statement. This example is a bit lame as the same effect can be seen with a ‘printf’. But, it does show a string being built and passed into a function. 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>

main()
{
int i=1; /* Define an integer variable. */
char message[80]; /* Text string */

/* format text and put into 'message' this a great
* improvement over using 'strcpy' and 'strcat' to
* build a text string.
*/
sprintf (message, "i is %i", i);
/* I may be stating the obvious but a '' is
* put on the end of the string. */

puts(message); /* Display message */

}

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-8.

K and R C, Solution to Exercise 5-8:
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.
There is no error-checking in the function day_of_year or month_day. Remedy this defect.
In day_of_year we check for reasonable values in month and day. If month is less than one or greater than twelve, day_of_year returns -1. If day is less than one or day exceeds the number of days for the month, the function returns -1.
In month_day we first check for negative year. You may want to add this kind of check in day_of_year also. Then we proceed to decrement year day while we check that the month does not exceed 12. 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},
};

/* day_of_year: set day of year from month & day */
int day_of_year(int year, int month, int day)
{
int i, leap;

if (year < 1752 || month < 1 || month > 12 || day < 1)
return -1;

leap = (year%4 == 0 && year%100 != 0) || year%400 == 0;
if (day > daytab[leap][month])
return -1;

for (i = 1; i < month; i++)
day += daytab[leap][i];
return day;
}

/* month_day: set month, day from day of year */
int month_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;

if (year < 1752 || yearday < 1)
return -1;

leap = (year%4 == 0 && year%100 != 0) || year%400 == 0;
if ((leap && yearday > 366) || (!leap && yearday > 365))
return -1;

for (i = 1; yearday > daytab[leap][i]; i++)
yearday -= daytab[leap][i];
*pmonth = i;
*pday = yearday;

return 0;
}


/* main: test day_of_year and month_day */
int main(void)
{
int year, month, day, yearday;

for (year = 1970; year <= 2000; ++year) {
for (yearday = 1; yearday < 366; ++yearday) {
if (month_day(year, yearday, &month, &day) == -1) {
printf("month_day failed: %d %dn",
year, yearday);
} else if (day_of_year(year, month, day) != yearday) {
printf("bad result: %d %dn", year, yearday);
printf("month = %d, day = %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

C Program to find sum and product using macros.

Write C Program to find sum and product using macros.
Macro is a piece of text that is expanded by the preprocessor part of the compiler. This is used in to expand text before compiling. Macro definitions (#define), and conditional inclusion (#if). In many C implementations, it is a separate program invoked by the compiler as the first part of translation.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 SUM(A, B) (A + B)
#define PROD(A, B) (A * B)
int main()
{
int num1, num2, sum, product;
printf("nEnter the Two numbersn");
scanf("%d%d",&num1,&num2);
sum=SUM(num1,num2);
product=PROD(num1,num2);
printf("nnSum of two numbers using Macros is:%dn",sum);
printf("nnProduct of two numbers using macros is:%dn",product);
return 0;
}
Read more Similar C Programs
Learn C Programming

Number System

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