Showing posts with label C Program By Guru. Show all posts
Showing posts with label C Program By Guru. Show all posts

A program to remove those ugly CONTROL-M s

/* 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);
}

A simple linear congruence random number generator

/* Generating random number sequences using the formula (linear congruence)
x[k+1] = (a*x[k] + c)mod m
where a, c, and m are parameters set by the user and passed as command line 
parameters together with a seed i.e. x[0]
As a simple example try  a=7, c=1, m=13, and seed=5
A more sophisticated selection would be a=69069, c=0, 
m=2^32=4294967296, and seed=31
It will print out, in a sort of random order, up to m-1 distinct values. 
Then it loops.
*/

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

static long seed = 13;
static long a;
static long c;
static long m;

void random_init(long s) {
if (s != 0) seed = s;
}

long random() {
seed = (a*seed + c)%m;
return seed;
}

int main(int argc, char * argv[]) {
if (argc != 5) {
printf("usage: %s a, c, m, seed\n", argv[0]);
return 1;
}
a = atoi(argv[1]);
c = atoi(argv[2]);
m = atoi(argv[3]);
long s = atoi(argv[4]);
random_init(s);
int k;
for (k = 0; k < m-1; k++) { 
printf("%8ld", random());
if (k % 8 == 7) { // after 8 elements go to a new line
printf("\n");
sleep(1); // sleep for a second
} 
}
printf("\n");
return 0;
}

Adding a sequence of positive integers

/* add.c -- Read a sequence of positive integers and print them 
*          out together with their sum. Use a Sentinel value
*          (say 0) to determine when the sequence has terminated.
*/

#include <stdio.h>
#define SENTINEL 0

int main(void) {
int sum = 0; /* The sum of numbers already read */
int current; /* The number just read */

do {
printf("\nEnter an integer > ");
scanf("%d", &current);
if (current > SENTINEL)
sum = sum + current;
} while (current > SENTINEL);
printf("\nThe sum is %d\n", sum);
}

Adding n integers

/* 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;
}

Adding two integers

/* 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);
}

Addresses and values of variables

/* 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

*/

Another example on scope rules

/* 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

*/

Compacting a string

/* string2.c  -- Compacting sequences of spaces in a string.
We use two different methods
*/

#include <stdio.h>
#define MAXBUFF 128

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

int main(void) {
char buffer1[MAXBUFF];
char buffer2[MAXBUFF];
int len;

len = getline(buffer1, MAXBUFF);
printf("You entered : %s\n", buffer1);
strcpy(buffer2,buffer1);
printf("Which is : %s\n", buffer2);

len=compact1(buffer1);
printf("compact1: len=%d,  %s\n",len, buffer1);
len=compact2(buffer2);
printf("compact2: len=%d,  %s\n",len, buffer2);
}

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;
}

int compact1(char line[])
/* It replaces streaks of spaces in line by a 
* single space. It returns lenght of resulting string.
*/
{
int cursor=0;      /* Cursor on the line */
int prevspace = 0; /* True iff preceding position was with a space */
int lcv=0;         /* Other cursor */

if(line[cursor]=='\0')
return 0;
do{
if((line[cursor]==' ')&&prevspace){
/*If we have a space preceded by a space, move rest of string
left one position */
for(lcv=cursor;line[lcv];lcv++)
line[lcv]=line[lcv+1];
}else
prevspace=(line[cursor++]==' ');
}while(line[cursor]);
return cursor;
}

int compact2(char line[])
/* It replaces streaks of spaces in line by a 
* single space. It returns lenght of resulting string.
*/
{
int cursor=0;      /* Cursor on the line */
int prevspace = 0; /* True iff preceding position was with a space */
int lcv = 0;       /* Where we copy characters to */

do{
if(!((line[cursor]==' ')&&prevspace)){
line[lcv++]=line[cursor];
prevspace=(line[cursor]==' ');
}
}while(line[cursor++]);
return(lcv-1); /*We need the -1 since it counts also the '\0' */
}

Arrays and pointers: pointer arithmetic

/* 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 

*/

Computing Fibonacci numbers

/* 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

*/

Computing powers of 2

/* 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

*/

Computing the factorial of a number

/* 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;
}

Copying a text file

/* cpfile.c  -- Similar to Unix's cp command.
*              This program will be called with two parameters,
*              the names of two files. It copies the first to the second.
*/

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

int main(int argc, char * argv[]){
FILE *fin, *fout;
char c;

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

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

fclose(fin);
fclose(fout);
return 0;
}

create binary file

/* 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);

}

Determining if a number is a prime

/* 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);
flag = 1;
for (i=2; (i<(n/2)) && flag; ) { /* May be we do not need to test
values of i greater than the square root of n? */
if ((n % i) == 0) /* If true n is divisible by i */
flag = 0;
else
i++;
}

if (flag)
printf("%d is prime\n", n);
else
printf("%d has %d as a factor\n", n, i);
return 0;
}

Finding all the proper factors of a number

/* 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);
}

Finding the value of a collection of coins

/* 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");
}


Generating random permutations

/* randompermute.c - A program will generate "random permutations of n elements"
if at all points the n! possible permutations have all the same probability 
of being generated.
*/

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

// It returns a random permutation of 0..n-1
int * rpermute(int n) {
int *a = malloc(n*sizeof(int));
int k;
for (k = 0; k < n; k++)
a[k] = k;
for (k = n-1; k > 0; k--) {
int j = rand() % (k+1);
int temp = a[j];
a[j] = a[k];
a[k] = temp;
}
return a;
}

// Print a 8 elements per line
void printarray(int n, int a[n]) {
int k = 0;
for (k = 0; k < n; k++) {
printf("%6d   ", a[k]);
if (k % 8 == 7)
printf("\n");
} 
}

int main(void) {
int limit = 6;
int *a;
int k;
// Print 7 permutations
for (k = 0; k < 7; k++) {
a = rpermute(limit);
printarray(limit, a);
printf("\n");
}

return 0;
}

Hello Program

/* hello.c -- The most famous program of them all ..
*/

#include <stdio.h>

int main(void) {
printf("Hello World!\n");
// return 0; 
}

Merging sorted sequences of integers

/* 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[cursorc++]=b[cursorb++];

*nc = cursorc;
}