Cprograms

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 78

/* power2.

c -- Print out powers of 2: 1, 2, 4,


8, .. up to 2^N
*/

#include <stdio.h>
#define N 16

int main(void) {
int n; /* The current exponent */
int val = 1; /* The current power of 2
*/

printf("\t n \t 2^n\n");
printf("\t================\n");
for (n=0; n<=N; n++) {
printf("\t%3d \t %6d\n", n, val);
val = 2*val;
}
return 0;
}

/* It prints out :

n 2^n
================
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
13 8192
14 16384
15 32768
16 65536

*/
/* homework1.c -- This is how the code for the
first homework
* appears when we have a single
block letter.
* In our Unix system you can
compile, link,
* load, and run this program
with the commands
* % cc homework1.c
* % a.out
*/

#include <stdio.h>

void blockg(void); /*Prototype for blockg


function */

int main (void) {


printf("\n");
blockg();
printf("\n");
}

/* Print out the Block letter g */


void blockg(void) {
printf("gggggg\n");
printf("g g\n");
printf("g\n");
printf("g ggg\n");
printf("g g\n");
printf("gggggg\n");
}

/* It prints out:
gggggg
g g
g
g ggg
g g
gggggg

*/
* homework1.c -- This is how the code for the
first homework
* appears when we have a single
block letter.
* In our Unix system you can
compile, link,
* load, and run this program
with the commands
* % cc homework1.c
* % a.out
*/

#include <stdio.h>

void blockg(void); /*Prototype for blockg


function */

int main (void) {


printf("\n");
blockg();
printf("\n");
}

/* Print out the Block letter g */


void blockg(void) {
printf("gggggg\n");
printf("g g\n");
printf("g\n");
printf("g ggg\n");
printf("g g\n");
printf("gggggg\n");
}

/* It prints out:

gggggg
g g
g
g ggg
g g
gggggg

*/
/* add2.c -- Add two numbers and print them out
together
with their sum
AUTHOR:
DATE:
*/

#include <stdio.h>

int main(void) {
int first, second;

printf("Enter two integers > ");


scanf("%d %d", &first, &second);
printf("The two numbers are: %d %d\n",
first, second);
printf("Their sum is %d\n", first+second);
}
/* addn.c -- Read a positive number N. Then
read N integers and
* print them out together with their
sum.
*/

#include <stdio.h>
int main(void) {
int n; /* The number of numbers to be
read */
int sum; /* The sum of numbers already
read */
int current; /* The number just read
*/
int lcv; /* Loop control variable, it
counts the number
of numbers already read */

printf("Enter a positive number n > ");


scanf("%d",&n); /* We should check that n is
really positive*/
sum = 0;
for (lcv=0; lcv < n; lcv++) {
printf("\nEnter an integer > ");
scanf("%d",&current);
/* printf("\nThe number was %d\n",
current); */
sum = sum + current;
}
printf("The sum is %d\n", sum);
return 0;
}
/* FILE: coins.c
* DETERMINES THE VALUE OF A COIN COLLECTION
* A Variation of the Hanly/Koffman book's
example
*/

#include <stdio.h>

void main ()
{
// Local data ...
int pennies; // input: count of
pennies
int nickels; // input: count of
nickels
int dimes; // input: count of
dimes
int quarters; // input: count of
quarters
int temp, left; // temporaries for
various
// computations

// Read in the count of quarters, dimes,


nickels and pennies.
printf("Enter the number of quarters, dimes,
nickels, and pennies: ");
scanf("%d %d %d %d", &quarters, &dimes,
&nickels, &pennies);

// Compute the total value in cents.


left = 25 * quarters + 10 * dimes + 5 *
nickels + pennies;

// Find and display the value in dollars


printf("Your collection is worth\n ");
temp = left / 100;
printf("\t%d dollar", temp);
if (temp==1)
printf(", ");
else
printf("s, ");
left = left % 100;

// Find and display the value left in


quarters
temp = left / 25;
printf("%d quarter", temp);
if (temp==1)
printf(", ");
else
printf("s, ");
left = left % 25;

// Find and display the value left in dimes


temp = left / 10;
printf("%d dime", temp);
// Here, just for fun, instead of using a
conditional statement,
// I use a conditional expression and string
concatenation
printf ((temp==1) ? ", " : "s, ");
left = left % 10;

// Find and display the value left in


nickels
temp = left / 5;
printf("%d nickel", temp);
if (temp==1)
printf(", and ");
else
printf("s, and ");
left = left % 5;

// Find and display the value left in


pennies
printf("%d penn", left);
if (left==1)
printf("y\n");
else
printf("ies\n");
}

/* factorial.c -- It computes repeatedly the


factorial of an integer entered
* by the user. It terminates when the
integer entered is not
* positive.
*/
#include <stdio.h>

int fact(int n);

int main(void) {
int current;

printf("Enter a positive integer [to


terminate enter non-positive] > ");
scanf("%d", &current);
while (current > 0) {
printf("The factorial of %d is %d\n",
current, fact(current));
printf("Enter a positive integer [to
terminate enter non-positive] > ");
scanf("%d", &current);
}
}

/* n is a positive integer. The function


returns its factorial */
int fact(int n) {
int lcv; /* loop control variable */
int p; /* set to the product of the
first lcv positive integers */

for(p=1, lcv=2; lcv <= n; p=p*lcv, lcv++);


return p;
}
/* prime1.c It prompts the user to enter an
integer N. It prints out
* if it is a prime or not. If not,
it prints out a factor of N.
*/

#include <stdio.h>

int main(void) {
int n;
int i;
int flag;

printf("Enter value of N > ");


scanf("%d", &n);

for (i=2, flag=1; (i<(n/2)) && flag; ) {


if ((n % i) == 0)
flag = 0;
else
i++;
}

if (flag)
printf("%d is prime\n", n);
else
printf("%d has %d as a factor\n", n, i);
}
/* factor1.c -- It prompts the user to enter an
integer N. It prints out
* if it is a prime or not. If not, it
prints out all of its
* proper factors.
*/

#include <stdio.h>

int main(void) {
int n,
lcv,
flag; /* flag initially is 1 and becomes 0
if we determine that n
is not a prime */

printf("Enter value of N > ");


scanf("%d", &n);
for (lcv=2, flag=1; lcv <= (n / 2); lcv++) {
if ((n % lcv) == 0) {
if (flag)
printf("The non-trivial factors of %d are:
\n", n);
flag = 0;
printf("\t%d\n", lcv);
}
}
if (flag)
printf("%d is prime\n", n);
}
/* true.c -- What are in C the values of TRUE
and FALSE?
*/

#include <stdio.h>

int main(void) {
printf("The value of 1<2 is %d\n", (1<2));
printf("The value of 2<1 is %d\n", (2<1));
}

/* The program prints out

The value of 1<2 is 1


The value of 2<1 is 0

*/
/* fibo.c -- It prints out the first N
Fibonacci
* numbers.
*/

#include <stdio.h>

int main(void) {
int n; /* The number of fibonacci
numbers we will print */
int i; /* The index of fibonacci
number to be printed next */
int current; /* The value of the (i)th
fibonacci number */
int next; /* The value of the (i+1)th
fibonacci number */
int twoaway; /* The value of the (i+2)th
fibonacci number */

printf("How many Fibonacci numbers do you


want to compute? ");
scanf("%d", &n);
if (n<=0)
printf("The number should be
positive.\n");
else {
printf("\n\n\tI \t Fibonacci(I)
\n\t=====================\n");
next = current = 1;
for (i=1; i<=n; i++) {
printf("\t%d \t %d\n", i, current);
twoaway = current+next;
current = next;
next = twoaway;
}
}
}

/* The output from a run of this program was:

How many Fibonacci numbers do you want to


compute? 9

I Fibonacci(I)
=====================
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34

*/
/* funcs.c -- Examples of function
declarations, definitions, and use
*/

#include <stdio.h>

/* Examples of declarations of functions */

void square1(void); /* Example of a function


without input parameters
and without return value */

void square2(int i); /* Example of a function


with one input parameter
and without return
value */

int square3(void); /* Example of a function


without input parameters
and with integer
return value */

int square4(int i); /* Example of a function


with one input parameter
and with integer return value
*/

int area(int b, int h); /* Example of a


function with two input parameters
and with integer return value
*/

/* Main program: Using the various functions */


int main (void) {
square1(); /* Calling the square1
function */
square2(7); /* Calling the square2
function using 7 as actual
parameter corresponding to the
formal parameter i */
printf("The value of square3() is %d\n",
square3()); /* Ysing the square3
function
*/
printf("The value of square4(5) is %d\n",
square4(5)); /* Using the square4
function with 5 as actual parameter
corresponding to i */
printf("The value of area(3,7) is %d\n",
area(3,7)); /* Using the area
function with 3, 7 as actual
parameters corresponding
to b, h respectively */
}

/* Definitions of the functions */

/* Function that reads from standard input an


integer and prints
it out together with its sum */
void square1(void){
int x;

printf("Please enter an integer > ");


scanf("%d", &x);
printf("The square of %d is %d\n", x, x*x);
}

/* Function that prints i together with its sum


*/
void square2(int i){
printf("The square of %d is %d\n", i, i*i);
}
/* Function that reads from standard input an
integer and returns
its square */
int square3(void){
int x;
printf("Please enter an integer > ");
scanf("%d", &x);
return (x*x);
}

/* Function that returns the square of i */


int square4(int i){
return (i*i);
}

/* Function that returns the area of the


rectangle with base b
and hight h */
int area(int b, int h){
return (b*h);
}

/* The output of this program is:

Please enter an integer > 3


The square of 3 is 9
The square of 7 is 49
Please enter an integer > 4
The value of square3() is 16
The value of square4(5) is 25
The value of area(3,7) is 21

*/
/* funcs.c -- More examples of functions
*/

#include <stdio.h>
int getint(void); /*It prompts user to enter an
integer, which it returns*/

int getmax(int a, int b, int c); /*It returns


value of largest of a, b, c*/

/* Main program: Using the various functions */


int main (void) {
int x, y, z;

x = getint();
y = getint();
z = getint();
printf("The largest of %d, %d, and %d is
%d\n", x, y, z, getmax(x,y,z));
}

int getint(void) {
int a;

printf("Please enter an integer > ");


scanf("%d", &a);
return(a);
}

int getmax(int a, int b, int c){


int m = a;

if (m<b)
m = b;
if (m<c)
m = c;
return(m);
}
/* scope1.c -- Simple example showing effects
of the scope rules
*/

#include <stdio.h>
int a=0; /* This is a global variable */

void foo(void);

int main(void) {
int a=2; /* This is a variable local to main
*/
int b=3; /* This is a variable local to main
*/

printf("1. main_b = %d\n", b);


printf("main_a = %d\n", a);
foo();
printf("2. main_b = %d\n", b);
}

void foo(void){
int b=4; /* This is a variable local to foo
*/

printf("foo_a = %d\n", a);


printf("foo_b = %d\n", b);
}
/* scope2.c -- Example on scope rules
*/

#include <stdio.h>
int x = 2;
int y = 3;
int z = 4;
void moo(int x, int *y){
int z;
x = x+3;
*y = *y+3;
z = z+3; /*Here z is the local z. Notice
that it has not been
initialized. As you see from the
output below
in this case it was implicitly
initialized to 0.
In general that is not the case
and the compiler
should give you a warning
*/
printf("moo : x = %1d, *y = %1d, y = %1d, z
= %1d\n", x,*y,y,z);
}
int main(void){
moo(x, &y);
printf("main: x = %1d1, y = %1d, z = %1d\n",
x,y,z);
}

/* The output is

moo : x = 5, *y = 6, y = 1073742056, z = 3
main: x = 21, y = 6, z = 4

*/
/* array.c -- Operations on arrays
*/

#include <stdio.h>

int main(void) {
int a[2] = {1,2}; /* The aggregates like
{1,2} are literals for arrays */
int b[2] = {2,3};
int i;

/* It is legal to use subscripts on arrays,


both on the left and on
* the right hand side of assignments. */
for(i=0;i<2;i++)
a[i]=b[i];
/* It is not legal to assign arrays, like in
a=b; */

/* The comparison of two distinct arrays with


the same content
* results in FALSE. So below we print "They
are not equal"
*/
if(a==b)
printf("They are equal\n");
else
printf("They are not equal\n");

/* The following comparison results in TRUE.


*/
if(a==a)
printf("Of course a is equal to a\n");
else
printf("No, a is not equal to a\n");
/* The behavior of comparison is explained
when we note that the
* comparison is a comparison of addresses,
not contents.
*/
/* We cannot print out an array as a single
unit. We have to print out
* its elements one at a time.
*/
for(i=0;i<2;i++)
printf("a[%1d] = %3d\n", i, a[i]);
}
/* array1.c -- Simple operations with arrays.
*/

#include <stdio.h>
#define N 10

void oneWay(void);
void anotherWay(void);
int main(void) {
printf("\noneWay:\n");
oneWay();
printf("\nantherWay:\n");
anotherWay();
}

/*Array initialized with aggregate */


void oneWay(void) {
int vect[N] = {1,2,3,4,5,6,7,8,9,0};
int i;

for (i=0; i<N; i++)


printf("i = %2d vect[i] = %2d\n", i,
vect[i]);
}

/*Array initialized with loop */


void anotherWay(void) {
int vect[N];
int i;

for (i=0; i<N; i++)


vect[i] = i+1;

for (i=0; i<N; i++)


printf("i = %2d vect[i] = %2d\n", i,
vect[i]);
}

/* The output of this program is

oneWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 0

antherWay:
i = 0 vect[i] = 1
i = 1 vect[i] = 2
i = 2 vect[i] = 3
i = 3 vect[i] = 4
i = 4 vect[i] = 5
i = 5 vect[i] = 6
i = 6 vect[i] = 7
i = 7 vect[i] = 8
i = 8 vect[i] = 9
i = 9 vect[i] = 10

*/
#define NMAX 10

void intSwap(int *x, int *y);


int getIntArray(int a[], int nmax, int
sentinel);
void printIntArray(int a[], int n);
void reverseIntArray(int a[], int n);

int main(void) {
int x[NMAX];
int hmny;

hmny = getIntArray(x, NMAX, 0);


printf("The array was: \n");
printIntArray(x,hmny);
reverseIntArray(x,hmny);
printf("after reverse it is:\n");
printIntArray(x,hmny);
}
void intSwap(int *x, int *y)
/* It swaps the content of x and y */
{
int temp = *x;
*x = *y;
*y = temp;
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

int getIntArray(int a[], int nmax, int


sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

void reverseIntArray(int a[], int n)


/* It reverse the order of the first n
elements of a */
{
int i;

for(i=0;i<n/2;i++){
intSwap(&a[i],&a[n-i-1]);
}
}
/* misc.c -- various C constructs */

#include <stdio.h>

int main(void) {
int answer;
short x = 1;
long y = 2;
float u = 3.0;
double v = 4.4;
long double w = 5.54;
char c = 'p';;

/* __DATE__, __TIME__, __FILE__, __LINE__ are


predefined symbols */
printf("Date : %s\n", __DATE__);
printf("Time : %s\n", __TIME__);
printf("File : %s\n", __FILE__);
printf("Line : %d\n", __LINE__);
printf("Enter 1 or 0 : ");
scanf("%d", &answer);

/* answer?"you said yes":"You said no" is a


conditional expression */
printf("%s\n", answer?"You sayd YES":"You
said NO");

/* The size of various types */


printf("The size of int %d\n",
sizeof(answer));
printf("The size of short %d\n", sizeof(x));
printf("The size of long %d\n", sizeof(y));
printf("The size of float %d\n", sizeof(u));
printf("The size of double %d\n", sizeof(v));
printf("The size of long double %d\n",
sizeof(w));
printf("The size of char %d\n", sizeof(c));

/*
The output from a run was:

Date : Feb 11 1997


Time : 13:51:31
File : white.c
Line : 20
Enter 1 or 0 : 1
You sayd YES
The size of int 4
The size of short 2
The size of long 8
The size of float 4
The size of double 8
The size of long double 8
The size of char 1

*/
/* addresses.c -- Playing with addresses of
variables and their contents:
* what is done by C with
variables, addresses, and values.
*/

#include <stdio.h>

void moo(int a, int * b);

int main(void) {
int x;
int *y;

x=1;
y=&x;
printf("Address of x = %d, value of x =
%d\n", &x, x);
printf("Address of y = %d, value of y = %d,
value of *y = %d\n", &y, y, *y);
moo(9,y);
}

void moo(int a, int *b){


printf("Address of a = %d, value of a =
%d\n", &a, a);
printf("Address of b = %d, value of b = %d,
value of *b = %d\n", &b, b, *b);
}

/* Output from running this program on my


computer:

Address of x = 536869640, value of x = 1


Address of y = 536869632, value of y =
536869640, value of *y = 1
Address of a = 536869608, value of a = 9
Address of b = 536869600, value of b =
536869640, value of *b = 1
*/
/* codes.c -- It prints out the numerical
codes of the printable ascii
* characters
*/

#include <stdio.h>

int main(void){
int c;

printf("\tCharacter Code\n"
"\t===============\n");
for (c=32; c<127; c++)
printf("\t %c %4d\n", c, c);
}

/* Here is the ouput from this program:

Character Code
===============
32
! 33
" 34
# 35
$ 36
% 37
& 38
' 39
( 40
) 41
* 42
+ 43
, 44
- 45
. 46
/ 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
] 93
^ 94
_ 95
` 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
{ 123
| 124
} 125
~ 126
*/
/* line.c -- It reads lines from input and
echoes them back.
*/

#include <stdio.h>

int main(void) {
char c;
int count;

for(;;){
count=0;
printf("Please enter a line [blank line to
terminate]> ");
do{
c=getchar();
putchar(c);
count++;
}while (c!='\n');
if(count==1)break;
}
}

/* linear.c -- Read an integer array and then


do linear searches.
*/

#include <stdio.h>

#define NMAX 10

int getIntArray(int a[], int nmax, int


sentinel);
void printIntArray(int a[], int n);
int linear(int a[], int n, int who);

int main(void) {
int x[NMAX];
int hmny;
int who;
int where;

hmny = getIntArray(x, NMAX, 0);


printf("The array was: \n");
printIntArray(x,hmny);
printf("Now we do linear searches on this
data\n");
do{
printf("Enter integer to search for [0 to
terminate] : ");
scanf("%d", &who);
if(who==0)break;
where = linear(x,hmny,who);
if (where<0){
printf("Sorry, %d is not in the
array\n",who);
}else
printf("%d is at position
%d\n",who,where);
}while(1);
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

int getIntArray(int a[], int nmax, int


sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

int linear(int a[], int n, int who)


/* Given the array a with n elements,
searches for who.
* It returns its position if found,
otherwise it returns
* -1.
*/
{
int lcv;
for (lcv=0;lcv<n;lcv++)
if(who == a[lcv])return lcv;
return (-1);
}
/* shift.c -- It reads a sequence of positive
integers. It stores it
* in an array, then it prompts the
user to enter an
* integer, and then rotates
clockwise the content of the
* array a corresponding number of
positions. The contents
* the array are printed out
whenever it changes.
* For example, if the sequence was
* 1,2,3,4,5
* and the number 3 is entered, the
array becomes
* 3,4,5,1,2
* and if the number 11 is now
entered, the array becomes
* 2,3,4,5,1
* and if the number -4 is now
entered, the array becomes
* 1,2,3,4,5
*/

#include <stdio.h>
#define MAXN 8

/* It prints the current content on the array a


with n elements */
void printarray(int a[], int n);
/* I will assume first that I have a number of
functions then I will
* write them.
*/

/* Given an array a with n values, shift


rotates
* its content m positions, clockwise.
*/
void shift(int a[], int n, int m);
/* getint prompts the user to enter a positive
integer and returns
* its value.
*/
int getint(void);

/* It requests the user to enter positive


integers and stores
* them in a. It returns in n the number of
integers stored
* in the array.
*/
void getarray(int a[], int *n);

int main(void) {
int table[MAXN]; /* array where we store the
sequence */
int howmany=0; /* number of elements in
sequence */
int amount; /* amount of shift */

getarray(table, &howmany);
if (howmany==0) {
printf("Sorry, you entered the null
sequence. Good bye.\n");
}else {
do {
printarray(table,howmany);
printf("By how much do you want to
shift[0 to terminate]? ");
scanf("%d",&amount);
if (amount!=0)
shift(table,howmany,amount);
}while(amount!=0);
}
}

/* Given an array a with n values, shift


rotates
* its content m positions, clockwise.
*/
void shift(int a[], int n, int m){
int temp[MAXN];
int lcv;

if (m<0)
m = n-(abs(m)%n);
for (lcv=0;lcv<n;lcv++)
temp[(lcv+m)%n] = a[lcv];
for (lcv=0; lcv<n;lcv++)
a[lcv]=temp[lcv];
}

/* getint prompts the user to enter a positive


integer and returns
* its value.
*/
int getint(void){
int answer;

printf("Please enter a positive integer


[<=0 to terminate] : ");
scanf("%d", &answer);
return answer;
}

/* It requests the user to enter positive


integers and stores
* them in a. It returns in n the number of
integers stored
* in the array.
*/
void getarray(int a[], int *n) {
int answer;
int i=0;

do {
answer = getint();
if (answer>0 && (i<MAXN))
a[i++]=answer;
}while(answer>0 && (i<MAXN));
*n = i;
}

/* It prints the current content of the array a


with n elements */
void printarray(int a[], int n) {
int lcv;

for (lcv=0;lcv<n;lcv++){
printf(" %d",a[lcv]);
}
printf("\n");
}
/* sieve.c - It prompts the user to enter an
integer N. It prints out
* It prints out all the primes up to
N included.
* It uses a sieve method. As primes
are found they are
* stored in an array PRIMES and used
as possible factors
* for the next potential prime.
*/

#include <stdio.h>

#define NPRIMES 1000


#define FALSE 0
#define TRUE 1

int main(void) {
int n;
int i,j;
int flag;
int primes[NPRIMES]; /*It will contain the
primes smaller than n
*that we have already
encountered*/
int level; /*1+Number of primes
currently in PRIMES*/

/*Introduction*/
printf("Enter value of N > ");
scanf("%d",&n);
level = 0;

/*Main body*/
for(i=2;i<=n;i++) {
for(j = 0, flag = TRUE; j<level && flag; j+
+)
flag = (i%primes[j]);
if (flag) { /*I is a prime */
printf("%12d\n", i);
if (level < NPRIMES)
primes[level++] = i;
}
}
}
/* string1.c -- Simple string operations
String literals.
printf, scanf, %s, %c
strlen
strcpy
strcmp
*/

#include <stdio.h>
#define MAXBUFF 128

int main(void) {
char c[] = "012345";
char line[MAXBUFF];
int lcv;
int cmp;

printf("sizeof(c)= %d\n", sizeof(c));


printf("sizeof(line)= %d\n", sizeof(line));
for (lcv=0; lcv<=strlen(c); lcv++)
printf("c[lcv]= %d = %c\n",c[lcv],c[lcv]);
printf("Please enter a string : ");
scanf("%s",line);
printf("strlen(line) = %d\n", strlen(line));
printf("line = [%s]\n",line);
cmp = strcmp(c,line);
if(cmp<0)
printf("%s is less than %s\n", c, line);
else if (c==0)
printf("%s is equal to %s\n", c, line);
else
printf("%s is greater than %s\n", c, line);
strcpy(line,c); /*copy the string c into
line */
cmp = strcmp(c,line);
if(cmp<0)
printf("%s is less than %s\n", c, line);
else if (cmp==0)
printf("%s is equal to %s\n", c, line);
else
printf("%s is greater than %s\n", c, line);
}

/* The output of this program:

sizeof(c)= 7
sizeof(line)= 128
c[lcv]= 48 = 0
c[lcv]= 49 = 1
c[lcv]= 50 = 2
c[lcv]= 51 = 3
c[lcv]= 52 = 4
c[lcv]= 53 = 5
c[lcv]= 0 =
Please enter a string : roses are red
strlen(line) = 5
line = [roses]
012345 is less than roses
012345 is equal to 012345

*/
/* getline.c -- Testing a function that reads a
line
* from input.
*/

#include <stdio.h>
#define MAXBUF 128

int getline(char line[], int nmax);

int main(void){
int len;
char buffer[MAXBUF];

while(1){
len = getline(buffer, MAXBUF);
if (len==0)break;
printf("len = %d, line = %s\n", len,
buffer);
};
}

int getline(char line[], int nmax)


/* It prompts user and reads up to nmax
* characters into line. It returns number
* of characters read. ['\n' terminates
the line]
*/
{
int len;
char c;
len = 0;
printf("Enter a string [CR to exit]: ");
while(((c=getchar())!='\n') && len<nmax-1)
line[len++]=c;
line[len]='\0';
return len;
}
/* counts.c - It contains a program that is
given as command parameter
* the name of a text file, say,
temp.dat. It will read each line
* of temp.dat and print out in
correspondence the number of
* characters and words on that
line. At the end it will print
* out the number of lines that were
read.
*/

#include <stdio.h>

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


FILE *fp;
int nchars, nwords, nlines;
int lastnblank; /* 0 iff the last
character was a space */
char c;

if(argc!=2){
printf("Usage: %s filename\n", argv[0]);
exit(0);
}
if((fp=fopen(argv[1],"r"))==NULL){
perror("fopen");
exit(0);
}
nchars=nwords=nlines=lastnblank=0;
while((c=getc(fp))!=EOF){
nchars++;
if (c=='\n'){
if (lastnblank)
nwords++;
printf("words=%d, characters=%d\n",
nwords, nchars);
nchars=nwords=lastnblank=0;
nlines++;
}else{
if (((c==' ')||(c=='\t'))&(lastnblank))
nwords++;
lastnblank=((c!=' ')&&(c!='\t'));
}
}
printf("lines=%d\n", nlines);
fclose(fp);
}
/* cpfile.c -- Similar to Unix's cp command.
* This program will be called
with two parameters,
* the names of two files. It
copies the second to the first.
*/

#include <stdio.h>

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


FILE *fin, *fout;
char c;

if (argc!=3){
printf("Usage: %s fileout filein\n", argc);
exit(0);
}
if ((fin=fopen(argv[2],"r"))==NULL){
perror("fopen filein");
exit(0);
}
if ((fout=fopen(argv[1],"w"))==NULL){
perror("fopen fileout");
exit(0);
}

while ((c=getc(fin))!=EOF)
putc(c,fout);

fclose(fin);
fclose(fout);
}
/* enum1.c -- Starting to use enumerated
types: Printing for each
* day of the week, today,
yesterday, and tomorrow, both
* as a string and as a number.
*/

#include <stdio.h>

/* Introducing an enumerated data type */


enum days
{monday,tuesday,wednesday,thursday,friday,satur
day,sunday};
typedef enum days days; // This allows us to
use "days" as an abbreviation
// for "enum days"

/* Two useful functions */


days yesterday(days today){
return (today+6)%7;
}
days tomorrow(days today){
return (today+1)%7;
}

// A useful array: thedays is an array of


constant (i.e you cannot
// modify them) pointers to constant (i.e. you
cannot modify them) strings
const char * const thedays[] =
{"monday", "tuesday",
"wednesday", "thursday",
"friday", "saturday",
"sunday"};

int main(void){
days today;

printf("today \tyesterday \ttomorrow\n"

"============================================\n
");
for (today=monday;today<=sunday;today++)
printf("%s = %d \t %s = %d \t %s = %d\n",
thedays[today], today,
thedays[yesterday(today)],
yesterday(today),
thedays[tomorrow(today)],
tomorrow(today));
}

/*
The output is:

today yesterday tomorrow


============================================
monday = 0 sunday = 6 tuesday = 1
tuesday = 1 monday = 0 wednesday = 2
wednesday = 2 tuesday = 1 thursday = 3
thursday = 3 wednesday = 2 friday = 4
friday = 4 thursday = 3 saturday = 5
saturday = 5 friday = 4 sunday = 6
sunday = 6 saturday = 5 monday = 0

*/
/* enum2.c -- Starting to use enumerated
types: Printing for each
* day of the week, today,
yesterday, and tomorrow, both
* as a string and as a number. We
use typedef
*/

#include <stdio.h>

/* Introducing an enumerated data type */


typedef enum
{monday,tuesday,wednesday,thursday,friday,satur
day,sunday} days;

/* Two useful functions */


days yesterday(days today);
days tomorrow(days today);

char *thedays[] = {"monday", "tuesday",


"wednesday", "thursday",
"friday", "saturday",
"sunday"};

int main(void){
days today;

printf("today \tyesterday \ttomorrow\n"

"============================================\n
");
for (today=monday;today<=sunday;today++)
printf("%s = %d \t %s = %d \t %s = %d\n",
thedays[today], today,
thedays[yesterday(today)],
yesterday(today),
thedays[tomorrow(today)],
tomorrow(today));
}

days yesterday(days today){


return (today+6)%7;
}
days tomorrow(days today){
return (today+1)%7;
}

/*
The output is:

today yesterday tomorrow


============================================
monday = 0 sunday = 6 tuesday = 1
tuesday = 1 monday = 0 wednesday = 2
wednesday = 2 tuesday = 1 thursday = 3
thursday = 3 wednesday = 2 friday = 4
friday = 4 thursday = 3 saturday = 5
saturday = 5 friday = 4 sunday = 6
sunday = 6 saturday = 5 monday = 0

*/
/* binary.c -- Read a sorted integer array and
then do binary searches.
* [We do not check to make sure
that the array is sorted.]
*/

#include <stdio.h>

#define NMAX 10

int getIntArray(int a[], int nmax, int


sentinel);
void printIntArray(int a[], int n);
int binary(int a[], int n, int who);

int main(void) {
int x[NMAX];
int hmny;
int who;
int where;

hmny = getIntArray(x, NMAX, 0);


printf("The array was: \n");
printIntArray(x,hmny);
if (hmny){
printf("Now we do binary searches on this
data\n");
do{
printf("Enter integer to search for [0 to
terminate] : ");
scanf("%d", &who);
if(who==0)break;
where = binary(x,hmny,who);
if (where<0){
printf("Sorry, %d is not in the
array\n",who);
}else
printf("%d is at position
%d\n",who,where);
}while(1);
}
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}
int getIntArray(int a[], int nmax, int
sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

int binary(int a[], int n, int who)


/* Given the array a with n elements,
searches for who.
* It returns its position if found,
otherwise it returns
* -1.
*/
{
int low = 0;
int high = n;
int middle;

while (low<high){
middle = (low+high)/2;
if (who<=a[middle])
high=middle;
else
low=middle+1;
}
if (who==a[low])
return low;
else
return -1;
}
* selection.c -- Read an integer array, print
it, then sort it and
* print it. Use the selection sort method.
*/

#include <stdio.h>

#define NMAX 10

int getIntArray(int a[], int nmax, int


sentinel);
void printIntArray(int a[], int n);
void selectionSort(int a[], int n);

int main(void) {
int x[NMAX];
int hmny;
int who;
int where;

hmny = getIntArray(x, NMAX, 0);


if (hmny==0)
printf("This is the empty array!\n");
else{
printf("The array was: \n");
printIntArray(x,hmny);
selectionSort(x,hmny);
printf("The sorted array is: \n");
printIntArray(x,hmny);
}
}
void printIntArray(int a[], int n)
/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

int getIntArray(int a[], int nmax, int


sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}
void selectionSort(int a[], int n)
/* It sorts in non-decreasing order the first N
positions of A. It uses
* the selection sort method.
*/
{
int lcv;
int rh; /*Elements in interval rh..n-1
are in their final position*/
int where; /*Position where we have current
maximum*/
int temp; /*Used for swapping*/

for(rh=n-1;rh>0;rh--){
/*Find position of largest element in range
0..rh*/
where = 0;
for (lcv=1;lcv<=rh;lcv++)
if (a[lcv]>a[where])
where = lcv;
temp = a[where];
a[where] = a[rh];
a[rh] = temp;
}
}
/* bubble.c -- Read an integer array, print it,
then sort it and
* print it. Use the bubble sort method.
*/

#include <stdio.h>

#define NMAX 10

int getIntArray(int a[], int nmax, int


sentinel);
void printIntArray(int a[], int n);
void bubbleSort(int a[], int n);
int main(void) {
int x[NMAX];
int hmny;
int who;
int where;

hmny = getIntArray(x, NMAX, 0);


if (hmny==0)
printf("This is the empty array!\n");
else{
printf("The array was: \n");
printIntArray(x,hmny);
bubbleSort(x,hmny);
printf("The sorted array is: \n");
printIntArray(x,hmny);
}
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

int getIntArray(int a[], int nmax, int


sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

void bubbleSort(int a[], int n)


/* It sorts in non-decreasing order the first N
positions of A. It uses
* the bubble sort method.
*/
{
int lcv;
int limit = n-1;
int temp;
int lastChange;

while (limit) {
lastChange = 0;
for (lcv=0;lcv<limit;lcv++)
/* Notice that the values in positions
LIMIT+1 .. N are in
* their final position, i.e. they are
sorted right */
if (a[lcv]>a[lcv+1]) {
temp = a[lcv];
a[lcv] = a[lcv+1];
a[lcv+1] = temp;
lastChange = lcv;
}
limit = lastChange;
}
}
/* number.c -- Reading and writing integer as
character sequences .
* Notice that the base for the
digits is the constant
* BASE that I have chosen to be
10. Of course, you
* use a different value. You might
even chose to
* have the base as a function
parameter.
*/

#include <stdio.h>
#include <assert.h>

#define BASE 10

// a is a string. cursor is a position in a


such that a[cursor] is a digit.
// Return the integer value represented by the
longest sequence of digits
// in a starting at cursor. On exit cursor will
be at the first position
// in a that does not contain a digit. Note
that we assume that the base for
// the number is 10.
int getNumberToken(char a[], int *cursor)
{
int value = 0;
assert((*cursor) >= 0 && (*cursor) <
strlen(a));
do
{
value = value*BASE + (int)(a[*cursor]) -
(int)('0');
(*cursor)++;
}
while (isdigit(a[*cursor]));
return value;
}

// value is a positive integer. a is a


character array with n positions.
// Store in a as a '\0' terminated string the
representation of value as
// a string in base BASE.
void putNumberToken(int value, char a[], int n)
{
int k;
int h, temp;
assert(value >= 0 && n > 0);
// We collect the desired string in reverse
order
for (k = 0; k < n-1; ++k)
{
a[k] = (char)(value%BASE + (int)'0');
value = value/BASE;
if (value == 0) break;
}
if (k == 0) // If value was 0 we still
return a '0'
a[k] = '0';
a[++k] = '\0';
// Now we put the string in the right order
for (h = 0; h < k/2; ++h)
{
temp = a[h];
a[h] = a[k-1-h];
a[k-1-h] = temp;
}
}
void main (void)
{
char s[] = "5432";
int k = 0;
int val = getNumberToken(s, &k);
char outs[256];

printf("val = %d, k = %d\n", val, k);


putNumberToken(val, outs, 256);
printf("val = %s\n", outs);
}
/* cpintarray.c -- Example showing how
addresses and arrays are alike
*/

#include <stdio.h>
#define SIZE 8

void cpIntArray(int *a, int *b, int n)


/*It copies n integers starting at b into a*/
{
for(;n>0;n--)
*a++=*b++;
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

int getIntArray(int a[], int nmax, int


sentinel)
/* It reads up to nmax integers and stores
then in a; sentinel
* terminates input. */
{
int n = 0;
int temp;

do {
printf("Enter integer [%d to terminate] :
", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}

int main(void){
int x[SIZE], nx;
int y[SIZE], ny;

printf("Read the x array:\n");


nx = getIntArray(x,SIZE,0);
printf("The x array is:\n");
printIntArray(x,nx);

printf("Read the y array:\n");


ny = getIntArray(y,SIZE,0);
printf("The y array is:\n");
printIntArray(y,ny);
cpIntArray(x+2,y+3,4);
/*Notice the expression 'x+2'. x is
interpreted as the address for
the beginning of the x array. +2 sais to
increment that address
by two units, in accordance with the type
of x, which is
an integer array. Thus we move from x to
two integer locations
past it, that is to the location of x[2].
The same reasoning applied
to 'y+3'.
*/
printf("Printing x after having copied 4
elements\n"
"from y starting at y[3] into x
starting at x[2]\n");
printIntArray(x,nx);
}

/* Here is the interaction in a run of this


program:

Read the x array:


Enter integer [0 to terminate] : 1
Enter integer [0 to terminate] : 3
Enter integer [0 to terminate] : 5
Enter integer [0 to terminate] : 7
Enter integer [0 to terminate] : 9
Enter integer [0 to terminate] : 11
Enter integer [0 to terminate] : 13
Enter integer [0 to terminate] : 15
Enter integer [0 to terminate] : 0
The x array is:
1 3 5 7 9
11 13 15
Read the y array:
Enter integer [0 to terminate] : 2
Enter integer [0 to terminate] : 4
Enter integer [0 to terminate] : 6
Enter integer [0 to terminate] : 8
Enter integer [0 to terminate] : 10
Enter integer [0 to terminate] : 12
Enter integer [0 to terminate] : 14
Enter integer [0 to terminate] : 16
Enter integer [0 to terminate] : 0
The y array is:
2 4 6 8 10
12 14 16
Printing x after having copied 4 elements
from y starting at y[3] into x starting at x[2]
1 3 8 10 12
14 13 15

*/
/* hmw10.c -- Outline of solution for homework
10
*/

#include <stdio.h>

#define ARRAYSIZE 2000


#define LINESIZE 65

typedef char linetype[LINESIZE];

int getline(FILE * fd, char buff[], int nmax){


/* It reads a line from fd and stores up to
nmax of
* its characters to buff.
*/
char c;
int n=0;

while ((c=getc(fd))!='\n'){
if(c==EOF)return EOF;
if(n<nmax)
buff[n++]=c;
}
buff[n]='\0';
return n;
}

int getStringArray(char *filename, linetype


table[], int nmax)
/* It reads up to nmax lines from file
called filename and
* stores them into table. It returns the
numbers of lines read
*/
{
FILE *fdu; /* File descriptor used for
filename */
int i, j;
char c;

if((fdu=fopen(filename,"r"))==NULL){
perror("fopen");
exit(1);
}
i=j=0;
while((c=getc(fdu))!=EOF){
if(i==nmax)break; /* We have filled up the
table */
if (c=='\n'){ /* We have finished reading a
line */
table[i++][j]='\0';
j=0;
}else if(j<LINESIZE)
table[i][j++]=c;
}
fclose(fdu);
return i;
}
void writeStringArray(char *filename, linetype
table[], int n)
/* It writes the first n lines of table
into the file
* called filename
*/
{
FILE *fdu; /* File descriptor used for
filename */
int i;

if((fdu=fopen(filename,"w"))==NULL){
perror("fopen");
exit(1);
}
for(i=0;i<n;i++)
fprintf(fdu, "%s\n", table[i]);
fclose(fdu);
}

void stringBubble(linetype table[], int n){


/* This function sorts the first n lines of
table.
* Here you see just the prototype, or stub,
of the function.
*/
}

int stringBinary(linetype table[], int n, char


who[]){
/* It searches the first n positions of table
looking for who.
* It uses binary search. It returns the
position where who is
* found, or -1 if not there. This is just
the prototype, or stub,
* of the function.
*/
return -1;
}

int main(void){
int n;
linetype linearray[ARRAYSIZE];
linetype who;
int where;
FILE *fdw; /* FILE descriptor used for
"who.dat" */
FILE *fda; /* File descriptor used for
"answers.dat" */

/* Read unsorted.dat into linearray and


return number of lines read */
n = getStringArray("unsorted.dat", linearray,
ARRAYSIZE);
if (n==0){
printf("The unsorted.dat file is empty.
Good bye.\n");
exit(0);
}
/* Sort the first n lines of linearray */
stringBubble(linearray,n);
/* Save the sorted array to sorted.dat */
writeStringArray("sorted.dat",linearray,n);
/* Open for reading who.dat */
if((fdw=fopen("who.dat","r"))==NULL){
perror("fopen");
exit(1);
}
/* Open for writing answers.dat */
if((fda=fopen("answers.dat","w"))==NULL){
perror("fopen");
exit(1);
}
while (getline(fdw,who,LINESIZE-1)!=EOF)
{ /* Read a line from "who.dat" */
where =
stringBinary(linearray,n,who); /* See where
it is in table */
fprintf(fda,"%d\n",where); /*
Write position to "answer.dat*/
}
fclose(fdw);
fclose(fda);
}
/* studentarray.c - Reads a file containing a
sequence of records
* representing students,
places them into an
* array, then writes that
array out to a new files.
* The names of the files are
passed in as command
* line parameters.
*/

#include <stdio.h>

#define SIZE 10
#define NAMESIZE 25

typedef struct {
char name[NAMESIZE];
int midterm;
int final;
int homeworks;
} student;

void writeStudentArray(char filename[], student


a[], int n)
/* n is the number of elements in the
array a.
* filename is the name of the file where
we will
* write.
*/
{
FILE *fd; /* File descriptor used for
filename */
int i;

if(n<=0)
return;
if((fd=fopen(filename,"w"))==NULL){
perror("fopen");
exit(1);
}
for (i=0;i<n;i++){
fprintf(fd,"%s %d %d %d\n",
a->name, a->midterm, a->final, a-
>homeworks);
a++;
}
fclose(fd);
}

int readStudentArray(char filename[], student


a[], int nmax)
/* It reads up to nmax student records
* from file filename and stores them in
a.
* It returns the number of records
actually read.
*/
{
FILE *fd; /* File descriptor used for
filename */
int i=0;

if((fd=fopen(filename,"r"))==NULL){
perror("fopen");
exit(1);
}
while(fscanf(fd,"%s %d %d %d",
a->name, &a->midterm, &a->final,
&a->homeworks)!=EOF){
if(++i==nmax)break; /* We have filled up
the table */
a++;
}
fclose(fd);
return i;
}

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


int n;
student table[SIZE];

if(argc!=3){
printf("Usage: %s infile outfile\n",
argv[0]);
exit(0);
}
n = readStudentArray(argv[1],table,SIZE);
writeStudentArray(argv[2],table,n);
}
/* merge.c -- Given two sorted sequences of
integers, it creates
* a sorted sequence consisting of
all their numbers.
*/

#include <stdio.h>

#define NMAX 10

void printIntArray(int a[], int n);


void merge(int c[], int *nc, int a[], int na,
int b[], int nb);

int main(void) {
int x[NMAX] = {1,3,5,6,7}; /* The first
sorted sequence */
int y[NMAX] = {2,3,4}; /* The second sorted
sequence */
int z[NMAX+NMAX]; /* The merge sequence */
int nz;

merge(z,&nz,x,5,y,3);
printIntArray(z,nz);
}

void printIntArray(int a[], int n)


/* n is the number of elements in the
array a.
* These values are printed out, five per
line. */
{
int i;

for (i=0; i<n; ){


printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}

void merge(int c[], int *nc, int a[], int na,


int b[], int nb){
/* Given sorted sequences a and b,
respectively with na and nb
* elements, it stores their merge sequence
in c and returns
* the total number of elements in nc
*/
int cursora, cursorb, cursorc;

cursora=cursorb=cursorc=0;
while((cursora<na)&&(cursorb<nb))
if (a[cursora]<=b[cursorb])
c[cursorc++]=a[cursora++];
else
c[cursorc++]=b[cursorb++];

while(cursora<na)
c[cursorc++]=a[cursora++];

while(cursorb<nb)
c[cursorb++]=b[cursorb++];

*nc = cursorc;
}
/* stringmerge.c -- Given two sorted files of
strings, it creates
* a sorted file consisting of all
their elements.
* The names of the files are passed
as command
* line parameters.
*/

#include <stdio.h>
#define MAXBUFFER 128

int getline(FILE * fd, char buff[], int nmax){


/* It reads a line from fd and stores up to
nmax of
* its characters to buff.
*/
char c;
int n=0;

while ((c=getc(fd))!='\n'){
if(c==EOF)return EOF;
if(n<nmax)
buff[n++]=c;
}
buff[n]='\0';
return n;
}

int stringMerge(char filename1[], char


filename2[] , char filename3[]) {
/* Given two sorted files of strings, called
filename1 and filename2,
* it writes their merged sequence to the
file filename3.
* It returns the total number of strings
written to filename3.
*/
FILE *fd1, *fd2, *fd3;
char buffer1[MAXBUFFER], buffer2[MAXBUFFER];
int ln1, ln2;
int n=0;

if ((fd1=fopen(filename1, "r"))==NULL) {
perror("fopen");
exit(1);
}
if ((fd2=fopen(filename2, "r"))==NULL) {
perror("fopen");
exit(1);
}
if ((fd3=fopen(filename3, "w"))==NULL) {
perror("fopen");
exit(1);
}

ln1 = getline(fd1,buffer1,MAXBUFFER-1);
ln2 = getline(fd2,buffer2,MAXBUFFER-1);

while ((ln1!=EOF) && (ln2!=EOF)){


if (strcmp(buffer1,buffer2)<=0){
fprintf(fd3, "%s\n", buffer1);
ln1 = getline(fd1,buffer1,MAXBUFFER-1);
}else{
fprintf(fd3, "%s\n", buffer2);
ln2 = getline(fd2,buffer2,MAXBUFFER-1);
}
n++;
}

while (ln1!=EOF){
fprintf(fd3, "%s\n", buffer1);
ln1=getline(fd1,buffer1,MAXBUFFER-1);
n++;
}

while (ln2!=EOF){
fprintf(fd3, "%s\n", buffer2);
ln2=getline(fd2,buffer2,MAXBUFFER-1);
n++;
}

fclose(fd1);
fclose(fd2);
fclose(fd3);
return n;
}

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


if(argc!=4){
printf("Usage: %s sortedfile1 sortedfile2
mergefile\n", argv[0]);
exit(0);
}
printf("We have %d merged records\n",
stringMerge(argv[1], argv[2], argv[3]));
}
/* sortmerge.c - Reads a file containing a
sequence of records
* representing students and
places them into an
* array table1. It does the
same for a second file
* placing result in table2. It
then sorts table1
* and table2 in non descending
order on the basis
* of their name fields. It now
stores the merge of
* the two sorted sequences in
an array table3.
* Finally it writes the result
to a third file.
* The names of the three files
are passed as
* command line parameters
*/

#include <stdio.h>

#define SIZE 10
#define NAMESIZE 25

typedef struct {
char name[NAMESIZE];
int midterm;
int final;
int homeworks;
} student;

void writeStudentArray(char filename[], student


a[], int n)
/* n is the number of elements in the
array a.
* filename is the name of the file where
we will
* write.
*/
{
FILE *fd; /* File descriptor used for
filename */
int i;

if(n<=0)
return;
if((fd=fopen(filename,"w"))==NULL){
perror("fopen");
exit(1);
}
for (i=0;i<n;i++){
fprintf(fd,"%s %d %d %d\n",
a->name, a->midterm, a->final, a-
>homeworks);
a++;
}
fclose(fd);
}

int readStudentArray(char filename[], student


a[], int nmax)
/* It reads up to nmax student records
* from file filename and stores them in
a.
* It returns the number of records
actually read.
* WARNING: We assume that the name of the
students contain no spaces.
*/
{
FILE *fd; /* File descriptor used for
filename */
int i=0;

if((fd=fopen(filename,"r"))==NULL){
perror("fopen");
exit(1);
}
while(fscanf(fd,"%s %d %d %d",
a->name, &a->midterm, &a->final,
&a->homeworks)!=EOF){
if(++i==nmax)break; /* We have filled up
the table */
a++;
}
fclose(fd);
return i;
}

void sortStudentArray(student table[], int n){


/* It sorts in nondecreasing order on the
basis of their
* names the first n records of table.
* WARNING: THIS IS A NULL STUB.
*/
}

int mergeStudentArray(student table3[], student


table1[], int n1,
student table2[], int n2){
/* It merges into table3 the first n1 student
records of table1
* and the first n2 student records of
table2. The records in
* table1 and table2 are sorted in
nondecreasing order of their
* name fields. It returns n1+n2.
* WARNING: THIS IS A STUB WHERE WE JUST
COPY, NOT MERGE.
*/
int i,j=0;

for(i=0;i<n1;i++){
table3[j++] = table1[i];
}
for(i=0;i<n2;i++){
table3[j++] = table2[i];
}
return n1+n2;
}
int main(int argc, char *argv[]){
int n1, /* Number of students in first
sequence */
n2, /* Number of students in second
sequence */
n3; /* Number of students in
resulting sequence */

student table1[SIZE], /* Students in first


sequence */
table2[SIZE], /* Students in second
sequence */
table3[SIZE+SIZE]; /* Students in merged
sequence */

if(argc!=4){
printf("Usage: %s unsfile1 unsfile2
outfile\n", argv[0]);
exit(0);
}
n1 = readStudentArray(argv[1],table1,SIZE);
sortStudentArray(table1,n1);
n2 = readStudentArray(argv[2],table2,SIZE);
sortStudentArray(table2,n2);
n3 = mergeStudentArray(table3, table1, n1,
table2, n2);
writeStudentArray(argv[3],table3,n3);
}
/* clean.c -- Given as command line parameter a
filename,
* it removes from that file all
occurrences of ^M
* If 'clean' is the executable
image of this
* program, you can use it as
follows:
* % clean dirtyfile >
cleanfile
*/

#include <stdio.h>
#define CONTROLM 13

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


char c;
FILE *fd;

if(argc!=2){
printf("Usage: %s filename\n", argv[0]);
exit(0);
}
if((fd = fopen(argv[1],"r"))==NULL){
perror("fopen");
exit(1);
}
while((c=getc(fd))!=EOF)
if (c!=CONTROLM)
putchar(c);
fclose(fd);
}
/* studentlist.c -- Reads a file containing a
sequence of records
* representing students,
places them into a linked
* list (a queue), then writes
that out to a new files.
* The names of the files are
passed in as command
* line parameters.
*/

#include <stdio.h>

#define NAMESIZE 25

typedef struct {
char name[NAMESIZE];
int midterm;
int final;
int homeworks;
} student;

typedef student *studentptr;

/***********THE QUEUE ABSTRACT DATA


TYPE************/

typedef struct node {


struct node *next;
student value;
}node;

typedef node *nodeptr;

typedef struct {
nodeptr head; /* Here we point to the oldest
element in the queue */
nodeptr tail; /* Here we point to the most
recent element in queue*/
} queue;

queue *init(void){
/* It creates, initializes, and returns a
queue */
queue *q;

if((q=(queue *)malloc(sizeof(queue)))==NULL){
perror("malloc");
exit(1);
}
q->head=NULL;
q->tail=NULL;
return q;
}
void final(queue *q){
/* It frees the queue q */
student s;

while(get(q,&s));
free(q);
}

void put(queue *q, studentptr s){


/* It inserts a new value *s in the queue q
*/
nodeptr p;

if ((p=(nodeptr)malloc(sizeof(node)))==NULL){
perror("malloc");
exit(1);
}
p->value=*s;
p->next = NULL;
if (q->head == NULL)
q->head = p;
else
q->tail->next = p;
q->tail = p;
}

int get(queue *q, studentptr s){


/*It obtains in s a student record from queue
and returns true
if such a record existed */
nodeptr p;

if(p=q->head){
q->head = q->head->next;
if((q->head)==NULL)
q->tail = NULL;
*s=p->value;
free(p);
return 1;
}else
return 0;
}

/*******END OF QUEUE ABSTRACT DATA


TYPE******************/

void writeStudentList(char filename[], queue


*q)
/* filename is the name of the file where
we will
* write sequentially the list accessed
from q.
*/
{
FILE *fd; /* File descriptor used for
filename */
student s;

if((fd=fopen(filename,"w"))==NULL){
perror("fopen");
exit(1);
}
while(get(q, &s)){
fprintf(fd,"%s %d %d %d\n",
s.name,
s.midterm,
s.final,
s.homeworks);
}
fclose(fd);
}

int readStudentList(char filename[], queue *q)


/* It reads student records from file
filename
* and stores them in q.
* It returns the number of records
actually read.
*/
{
FILE *fd; /* File descriptor used for
filename */
int i=0;
student temp;

if((fd=fopen(filename,"r"))==NULL){
perror("fopen");
exit(1);
}
while(fscanf(fd,"%s %d %d %d",
temp.name,
&temp.midterm,
&temp.final,
&temp.homeworks)!=EOF){
put(q,&temp);
i++;
}
fclose(fd);
return i;
}

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


int n;
queue *q;

q = init();
if(argc!=3){
printf("Usage: %s infile outfile\n",
argv[0]);
exit(0);
}
n = readStudentList(argv[1],q);
writeStudentList(argv[2],q);
final(q);
}
/* makebinfile.c - Reads a file containing a
sequence of text records
* and writes it out to a new
binary files.
* The names of the files are
passed in as command
* line parameters.
*/

#include <stdio.h>

#define SIZE 10
#define NAMESIZE 25

typedef struct {
char name[NAMESIZE];
int midterm;
int final;
int homeworks;
} student;

int writeastudent(FILE *fdout, student * who){


/* Write to an open binary file fdout the
content of who.
* Return the number of bytes that were
written out.
*/

char * p; /* Cursor in outputting a


byte at a time */
char * limit = ((char *)who)+sizeof(student);
/*Address just past who */

for (p=(char *)who;p<limit;p++){


fputc(*p, fdout);
}
return (limit - (char *)who);
}

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


int n = 0; /* Number of records read
*/
int m; /* Number of bytes in a
record */
student who; /* Buffer for a record */

FILE *fdin; /* File descriptor for input


file */
FILE *fdout; /* File descriptor for output
file */

if(argc!=3){
printf("Usage: %s infile outfile\n",
argv[0]);
exit(0);
}

if((fdin=fopen(argv[1],"r"))==NULL){
perror("fopen");
exit(1);
}

if((fdout=fopen(argv[2],"w"))==NULL){
perror("fopen");
exit(1);
}

while(fscanf(fdin,"%s %d %d %d",
who.name, &who.midterm, &who.final,
&who.homeworks)!=EOF){
m = writeastudent(fdout, &who);
printf("m=%d\n", m);
n++;
}

printf("n=%d\n", n);

fclose(fdin);
fclose(fdout);
}

You might also like