C Program of priority queue using linked list


/*Program of priority queue using linked list*/
#include<stdio.h>
#include<stdlib.h>

struct node
{
int priority;
int info;
struct node *link;
}*front=NULL;

void insert(int item, int item_priority);
int del();
void display();
int isEmpty();

main()
{
int choice,item,item_priority;
while(1)
{
printf(“1.Insert\n”);
printf(“2.Delete\n”);
printf(“3.Display\n”);
printf(“4.Quit\n”);
printf(“Enter your choice : “);
scanf(“%d”, &choice);

switch(choice)
{
case 1:
printf(“Input the item to be added in the queue : “);
scanf(“%d”,&item);
printf(“Enter its priority : “);
scanf(“%d”,&item_priority);
insert(item, item_priority);
break;
case 2:
printf(“Deleted item is %d\n”,del());
break;
case 3:
display();
break;
case 4:
exit(1);
default :
printf(“Wrong choice\n”);
}/*End of switch*/
}/*End of while*/
}/*End of main()*/

void insert(int item,int item_priority)
{
struct node *tmp,*p;

tmp=(struct node *)malloc(sizeof(struct node));
if(tmp==NULL)
{
printf(“Memory not available\n”);
return;
}
tmp->info=item;
tmp->priority=item_priority;
/*Queue is empty or item to be added has priority more than first element*/
if( isEmpty() || item_priority < front->priority )
{
tmp->link=front;
front=tmp;
}
else
{
p = front;
while( p->link!=NULL && p->link->priority<=item_priority )
p=p->link;
tmp->link=p->link;
p->link=tmp;
}
}/*End of insert()*/

int del()
{
struct node *tmp;
int item;
if( isEmpty() )
{
printf(“Queue Underflow\n”);
exit(1);
}
else
{
tmp=front;
item=tmp->info;
front=front->link;
free(tmp);
}
return item;
}/*End of del()*/

int isEmpty()
{
if( front == NULL )
return 1;
else
return 0;

}/*End of isEmpty()*/

void display()
{
struct node *ptr;
ptr=front;
if( isEmpty() )
printf(“Queue is empty\n”);
else
{    printf(“Queue is :\n”);
printf(“Priority       Item\n”);
while(ptr!=NULL)
{
printf(“%5d        %5d\n”,ptr->priority,ptr->info);
ptr=ptr->link;
}
}
}/*End of display() */

C Program of reversing a string using stack


 

/*Program of reversing a string using stack */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX 20

int top = -1;
char stack[MAX];
char pop();
void push(char);

main()
{
char str[20];
unsigned int i;
printf(“Enter the string : ” );
gets(str);
/*Push characters of the string str on the stack */
for(i=0;i<strlen(str);i++)
push(str[i]);
/*Pop characters from the stack and store in string str */
for(i=0;i
str[i]=pop();
printf(“Reversed string is : “);
puts(str);
}/*End of main()*/

void push(char item)
{
if(top == (MAX-1))
{
printf(“Stack Overflow\n”);
return;
}
stack[++top] =item;
}/*End of push()*/

char pop()
{
if(top == -1)
{
printf(“Stack Underflow\n”);
exit(1);
}
return stack[top–];
}/*End of pop()*/

 

C program for Linked Lists Using Recursion for all operations


/*Linked list using Recursion*/
#include<stdio.h>
#include<stdlib.h>

struct node
{
int info;
struct node *link;
};
struct node *create_list(struct node *start);
void display(struct node *ptr);
void Rdisplay(struct node *ptr);
int length(struct node *ptr);
int sum (struct node *ptr);
int search(struct node *ptr, int item );
struct node *insertLast(struct node *ptr, int value);
struct node *delLast(struct node *ptr );
struct node *reverse(struct node *ptr);

main()
{
struct node *start=NULL;
int choice,data;

while(1)
{
printf(“\n1.Create List\n”);
printf(“\n2.Display\n”);
printf(“\n3.Display in reverse order\n”);
printf(“\n4.Count\n”);
printf(“\n5.Sum of elements\n”);
printf(“\n6.Search\n”);
printf(“\n7.Insert at last\n”);
printf(“\n8.Delete the last node\n”);
printf(“\n9.Reverse the list\n”);
printf(“\n10.Quit\n”);

printf(“\n\nEnter your choice : “);
scanf(“%d”,&choice);
printf(“\n”);
switch(choice)
{
case 1:
start=create_list(start);
break;
case 2:
display(start);
printf(“\n\n”);
break;
case 3:
Rdisplay(start);
printf(“\n\n”);
break;
case 4:
printf(“\nNumber of elements = %d\n\n”,length(start));
break;
case 5:
printf(“\nSum of elements = %d\n\n”,sum(start));
break;
case 6:
printf(“\nEnter the element to be searched : “);
scanf(“%d”,&data);
if( search(start,data) == 1 )
printf(“\nElement present\n\n”);
else
printf(“\nElement not present\n\n”);
break;
case 7:
printf(“\nEnter the element to be inserted : “);
scanf(“%d”,&data);
start=insertLast(start,data);
break;
case 8:
start=delLast(start);
printf(“\nLast node deleted……\n”);
break;
case 9:
start=reverse(start);
break;
case 10:
exit(1);
default:
printf(“\nWrong choice\n”);
}/*End of switch */
}/*End of while */
}/*End of main()*/

struct node *create_list(struct node *start)
{
int i,n,value;
struct node *q,*tmp;
printf(“\nEnter the number of nodes : “);
scanf(“%d”,&n);
start=NULL;
for(i=1;i<=n;i++)
{
printf(“\nEnter the element to be inserted : “);
scanf(“%d”,&value);

tmp= malloc(sizeof(struct node));
tmp->info=value;
tmp->link=NULL;

if(start==NULL) /*If list is empty */
start=tmp;
else
{ /*Element inserted at the end */
q=start;
while(q->link!=NULL)
q=q->link;
q->link=tmp;
}
}
return start;
}/*End of create_list()*/

void display(struct node *ptr)
{
if(ptr==NULL)
return;
printf(“%3d”,ptr->info);
display(ptr->link);
}/*End of display()*/

void Rdisplay(struct node *ptr)
{
if(ptr==NULL)
return;
Rdisplay(ptr->link);
printf(“%3d”,ptr->info);
}/*End of Rdisplay()*/

int length(struct node *ptr)
{
if(ptr==NULL)
return 0;
return 1 + length(ptr->link);

}/*End of length()*/

int sum (struct node *ptr)
{
if (ptr == NULL)
return 0;
return ptr->info + sum(ptr->link);
}/*End of sum()*/

int search(struct node *ptr, int item )
{
if(ptr==NULL)
return 0;
if( ptr->info == item )
return 1;
return search(ptr->link, item);
}/*End of search()*/

struct node *insertLast(struct node *ptr, int item)
{
struct node *temp;
if (ptr == NULL)
{
temp = malloc(sizeof(struct node));
temp->info = item;
temp->link = NULL;
return temp;
}
ptr->link = insertLast(ptr->link, item);
return ptr;
}/*End of insertLast()*/

struct node *delLast(struct node *ptr )
{
if( ptr->link == NULL )
{
free(ptr);
return NULL;
}
ptr->link = delLast(ptr->link);
return ptr;
}/*End of delLast()*/

struct node *reverse(struct node *ptr)
{
struct node *temp;
if( ptr->link == NULL )
return ptr;
temp=reverse(ptr->link);
ptr->link->link=ptr;
ptr->link=NULL;
return temp;
}/*End of reverse()*/

Program to transpose a sparse matrix using Linked Lists


 

#include <stdio.h>
#include <conio.h>
#include <malloc.h>

#define MAX1 3
#define MAX2 3

/* structure for col headnode */
struct cheadnode
{
int colno ;
struct node *down ;
struct cheadnode *next ;
} ;

/* structure for row headnode */
struct rheadnode
{
int rowno ;
struct node * right ;
struct rheadnode *next ;
} ;

/* structure for node to store element */
struct node
{
int row ;
int col ;
int val ;
struct node *right ;
struct node *down ;
} ;

/* structure for special headnode */
struct spmat
{
struct rheadnode *firstrow ;
struct cheadnode *firstcol ;
int noofrows ;
int noofcols ;
} ;

struct sparse
{
int *sp ;
int row ;
struct spmat *smat ;
struct cheadnode *chead[MAX2] ;
struct rheadnode *rhead[MAX1] ;
struct node *nd ;
} ;

void initsparse ( struct sparse * ) ;
void create_array ( struct sparse * ) ;
void display ( struct sparse ) ;
int count ( struct sparse ) ;
void create_triplet ( struct sparse *, struct sparse ) ;
void create_llist ( struct sparse * ) ;
void insert ( struct sparse *, struct spmat *, int, int, int ) ;
void show_llist ( struct sparse ) ;
void delsparse ( struct sparse * ) ;

void main( )
{
struct sparse s1, s2 ;

clrscr( ) ;

initsparse ( &s1 ) ;
initsparse ( &s2 ) ;

create_array ( &s1 ) ;

printf ( “\nElements in sparse matrix: ” ) ;
display ( s1 ) ;

create_triplet ( &s2, s1 ) ;

create_llist ( &s2 ) ;
printf ( “\n\nInformation stored in linked list : ” ) ;
show_llist ( s2 ) ;

delsparse ( &s1 ) ;
delsparse ( &s2 ) ;

getch( ) ;
}

/* initializes structure elements */
void initsparse ( struct sparse *p )
{
int i ;
/* create row headnodes */
for ( i = 0 ; i < MAX1 ; i++ )
p -> rhead[i] = ( struct rheadnode * ) malloc ( sizeof ( struct rheadnode ) ) ;

/* initialize and link row headnodes together */
for ( i = 0 ; i < MAX1 – 1 ; i++ )
{
p -> rhead[i] -> next = p -> rhead[i + 1] ;
p -> rhead[i] -> right = NULL ;
p -> rhead[i] -> rowno = i ;
}
p -> rhead[i] -> right = NULL ;
p -> rhead[i] -> next = NULL ;

/* create col headnodes */
for ( i = 0 ; i < MAX1 ; i++ )
p -> chead[i] = ( struct cheadnode * ) malloc ( sizeof ( struct cheadnode ) ) ;

/* initialize and link col headnodes together */
for ( i = 0 ; i < MAX2 – 1 ; i++ )
{
p -> chead[i] -> next = p -> chead[i + 1] ;
p -> chead[i] -> down = NULL ;
p -> chead[i] -> colno = i ;
}
p -> chead[i] -> down = NULL ;
p -> chead[i] -> next = NULL ;

/* create and initialize special headnode */

p -> smat = ( struct spmat * ) malloc ( sizeof ( struct spmat ) ) ;
p -> smat -> firstcol = p -> chead[0] ;
p -> smat -> firstrow = p -> rhead[0] ;
p -> smat -> noofcols = MAX2 ;
p -> smat -> noofrows = MAX1 ;
}

/* creates, dynamically the matrix of size MAX1 x MAX2 */
void create_array ( struct sparse *p )
{
int n, i ;

p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ;

/* get the element and store it */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
printf ( “Enter element no. %d:”, i ) ;
scanf ( “%d”, &n ) ;
* ( p -> sp + i ) = n ;
}
}

/* displays the contents of the matrix */
void display ( struct sparse s )
{
int i ;

/* traverses the entire matrix */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % MAX2 == 0 )
printf ( “\n” ) ;
printf ( “%d\t”, * ( s.sp + i ) ) ;
}
}

/* counts the number of non-zero elements */
int count ( struct sparse s )
{
int cnt = 0, i ;

for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
if ( * ( s.sp + i ) != 0 )
cnt++ ;
}
return cnt ;
}

/* creates an array of triplet containing info. about non-zero elements */
void create_triplet ( struct sparse *p, struct sparse s )
{
int r = 0 , c = -1, l = -1, i ;

p -> row = count ( s ) ;
p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ;

for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
c++ ;
/* sets the row and column values */
if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) )
{
r++ ;
c = 0 ;
}

/* checks for non-zero element. Row, column and
non-zero element value is assigned to the matrix */
if ( * ( s.sp + i ) != 0 )
{
l++ ;
* ( p -> sp + l ) = r ;
l++ ;
* ( p -> sp + l ) = c ;
l++ ;
* ( p -> sp + l ) = * ( s.sp + i ) ;
}
}
}

/* stores information of triplet in a linked list form */
void create_llist ( struct sparse *p )
{
int j = 0, i ;
for ( i = 0 ; i < p -> row ; i++, j+= 3 )
insert ( p, p -> smat, * ( p -> sp + j ), * ( p -> sp + j + 1 ),
* ( p -> sp + j + 2) ) ;
}

/* inserts element to the list */
void insert ( struct sparse *p, struct spmat *smat , int r, int c, int v )
{
struct node *temp1, *temp2 ;
struct rheadnode *rh ;
struct cheadnode *ch ;
int i, j ;

/* allocate and initialize memory for the node */

p -> nd = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
p -> nd -> col = c ;
p -> nd -> row = r ;
p -> nd -> val = v ;

/* get the first row headnode */

rh = smat -> firstrow ;

/* get the proper row headnode */
for ( i = 0 ; i < r ; i++ )
rh = rh -> next ;
temp1 = rh -> right ;

/* if no element added in a row */
if ( temp1 == NULL )
{
rh -> right = p -> nd ;
p -> nd -> right = NULL ;
}
else
{
/* add element at proper position */
while ( ( temp1 != NULL ) && ( temp1 -> col < c ) )
{
temp2 = temp1 ;
temp1 = temp1 -> right ;
}
temp2 -> right = p -> nd ;
p -> nd -> right = NULL ;
}

/* link proper col headnode with the node */

ch = p -> smat -> firstcol ;
for ( j = 0 ; j < c ; j++ )
ch = ch -> next ;
temp1 = ch -> down ;

/* if col not pointing to any node */
if ( temp1 == NULL )
{
ch -> down = p -> nd ;
p -> nd -> down = NULL ;
}
else
{
/* link previous node in column with next node in same column */
while ( ( temp1 != NULL ) && ( temp1 -> row < r ) )
{
temp2 = temp1 ;
temp1 = temp1 -> down ;
}
temp2 -> down = p -> nd ;
p -> nd -> down = NULL ;
}
}

void show_llist ( struct sparse s )
{
struct node *temp ;
/* get the first row headnode */
int r = s.smat -> noofrows ;
int i ;

printf ( “\n” ) ;

for ( i = 0 ; i < r ; i++ )
{
temp = s.rhead[i] -> right ;
if ( temp != NULL )
{
while ( temp -> right != NULL )
{
printf ( “Row: %d Col: %d Val: %d\n”, temp -> row, temp -> col,
temp -> val ) ;
temp = temp -> right ;
}
if ( temp -> row == i )
printf ( “Row: %d Col: %d Val: %d\n”, temp -> row, temp -> col,
temp -> val ) ;
}
}
}

/* deallocates memory */
void delsparse ( struct sparse *p )
{
int r = p -> smat -> noofrows ;
struct rheadnode *rh ;
struct node *temp1, *temp2 ;
int i, c ;

/* deallocate memeory of nodes by traversing rowwise */
for ( i = r – 1 ; i >= 0 ; i– )
{
rh = p -> rhead[i] ;
temp1 = rh -> right ;

while ( temp1 != NULL )
{
temp2 = temp1 -> right ;
free ( temp1 ) ;
temp1 = temp2 ;
}
}

/* deallocate memory of row headnodes */
for ( i = r – 1 ; i >= 0 ; i– )
free ( p -> rhead[i] ) ;

/* deallocate memory of col headnodes */

c = p -> smat -> noofcols ;
for ( i = c – 1 ; i >= 0 ; i– )
free ( p -> chead[i] ) ;
}

\n

Transposing a Sparse Matrix Using Array [Part 1-Long]


 

#include<stdio.h>
#include<conio.h>
// transpose for the sparse matrix
main()
{
//clrscr();
int a[10][10],b[10][10];
int m,n,p,q,t,col;
int i,j;

printf(“enter the no of row and columns :\n”);
scanf(“%d %d”,&m,&n);

// assigning the value of matrix

for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
printf(“a[%d][%d]= “,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“\n\n”);

//displaying the matrix

printf(“\n\nThe matrix is :\n\n”);

for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
t=0;

printf(“\n\nthe non zero value matrix are :\n\n”);

for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{

// accepting only non zero value
if(a[i][j]!=0)
{
t=t+1;
b[t][1]=i;
b[t][2]=j;
b[t][3]=a[i][j];
} }
}

// displaying the matrix of non-zero value

printf(“\n”);
printf(“a[0 %d %d %d\n”,m,n,t);

for(i=1;i<=t;i++)
{
printf(“a[%d %d %d %d \n”,i,b[i][1],b[i][2],b[i][3]);
}

b[0][1]=n; b[0][2]=m; b[0][3]=t;
q=1;

// transpose of the matrix

printf(“\n\nthe transpose of the matrix :\n “);

if(t>0)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=t;j++)
{
if(b[j][2]==i)
{
a[q][1]=b[j][2]; a[q][2]=b[j][1];
a[q][3]=b[j][3]; q=q+1;
} }
} }

printf(“\n\n”);
printf(“a[0 %d %d %d\n”,b[0][1],b[0][2],b[0][3]);

for(i=1;i<=t;i++)
{
printf(“a[%d %d %d %d\n”,i,a[i][1],a[i][2],a[i][3]);
}
getch();
}

\n

Infix to Postfix Expression conversion using stacks


 

Illustration of infix notation
Illustration of infix notation (Photo credit: Wikipedia)

Here is and application of stacks in data structures in the conversion of infix to postfix expression

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

#define N 64

#define LP 10

#define RP 20

#define OPERATOR 30
#define OPERAND 40

#define LPP 0
#define AP 1
#define SP AP
#define MP 2
#define DP MP
#define REMP 2

#define NONE 9

static char infix[N+1],stack[N],postfix[N+1];
static int top;

void infixtopostfix(void);
int gettype(char);
void push(char);
char pop(void);
int getprec(char);
main()
{
char ch;
do
{
top=-1;
printf(“\nEnter an infix expression\n”);
fflush(stdin);
gets(infix);
infixtopostfix();
printf(“\ninfix = %s\npost fix =%s\n”,infix,postfix);
printf(“\nDo you wish to continue\n”);
ch=getche();
}while(ch==’Y’ || ch==’y’);
}

void infixtopostfix(void)
{
int i,p,l,type,prec;
char next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP:
push(infix[i]);
break;
case RP:
while((next=pop())!='(‘)
postfix[p++]=next;
break;
case OPERAND:
postfix[p++]=infix[i];
break;
case OPERATOR:
prec=getprec(infix[i]);
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}
while(top>-1)
postfix[p++]=pop();
postfix[p]=”;
}

int gettype(char sym)
{
switch(sym)
{
case ‘(‘:
return(LP);
case ‘)’:
return(RP);
case ‘+’:
case ‘-‘:
case ‘*’:
case ‘/’:
case ‘%’:
return(OPERATOR);
default :
return(OPERAND);
}
}

void push(char sym)
{
if(top>N)
{
printf(“\nStack is full\n”);
exit(0);
}
else
stack[++top]=sym;
}

char pop(void)
{
if(top<=-1)
{
printf(“\nStack is empty\n”);
exit(0);
}
else
return(stack[top–]);
}

int getprec(char sym)
{
switch(sym)
{
case ‘(‘:
return(LPP);
case ‘+’:
return(AP);
case ‘-‘:
return(SP);
case ‘*’:
return(MP);
case ‘/’:
return(DP);
case ‘%’:
return(REMP);
default :
return(NONE);
}
getch();
}

\n

String Pattern Matching in C using pointers


 

Block diagrams of (Left) pattern matching and ...
Block diagrams of (Left) pattern matching and substitution method and (Right) soft pattern matching method. (Photo credit: Wikipedia)

 

String Pattern Matching Program in C using Pointers

 

Its an application of Arrays

 

 

#include<stdio.h>
#include<conio.h>
int match(char*, char*);

main()
{
char a[100], b[100];
int position;

printf(“Enter some text\n”);
gets(a);

printf(“Enter a string to find\n”);
gets(b);

position = match(a, b);

if(position!=-1)
printf(“Found at location %d\n”, position+1);
else
printf(“Not found.\n”);

getch();
}

int match(char *a, char *b)
{
int c;
int position = 0;
char *x, *y;

x = a;
y = b;

while(*a)
{
while(*x==*y)
{
x++;
y++;
if(*x==”||*y==”)
break;
}
if(*y==”)
break;

a++;
position++;
x = a;
y = b;
}
if(*a)
return position;
else
return -1;
}

 

 

 

\n

 

Array Complete Program using C[DATA STRUCTURE]


 

Real (Laplace) spherical harmonics for to (top...
Real (Laplace) spherical harmonics for to (top to bottom) and to (left to right). The negative order harmonics are rotated about the axis by with respect to the positive order ones. (Photo credit: Wikipedia)

 

Here is what I present Before you is a complete array program where all operations of arrays are included eg:-

 

  1. Insertion

  2. Deletion

  3. Searching

  4. Sorting

  5. Dispay

 

#include <stdio.h>
#include <conio.h>
int n; //size of array

int BSearch(int *a,int ITEM)
{
int beg=0,end=n-1;
int mid;

while( beg<=end )
{
mid=(beg+end)/2;
if(a[mid]==ITEM)
return mid;
else if( a[mid] < ITEM )
beg=mid+1;
else
end=mid-1;
}

return -1;
}

void SSort(int *a)
{
int i,j,temp;

for(i=0; i
{
for(j=i+1; j
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

}

void DEL(int *a, int ITEM)
{
int i;
int pos=BSearch(a, ITEM);

if(pos!=-1)
{
for(i=pos; i
a[i]=a[i+1];
n–;
printf(“\n Item Deleted. “);
}
else
printf(“\n Item not found. “);
}

void INS(int *a, int ITEM)
{
int pos,i;

//Finding the proper position for Sorted Array
if(ITEM>a[n-1])
pos=n;
else if(ITEM<a[0])
pos=0;
else
{
for(i=0; i
if(a[i]<=ITEM && a[i+1]>=ITEM)
{
pos=i+1;
break;
}
}

//Shifting of elements to Insert the element.
for(i=n; i>pos; i–)
a[i]=a[i-1];

a[pos]=ITEM;
n++;
printf(“\n Item Inserted. “);
}

void Display(int *a)
{
int i;
for(i=0; i<n; i++)
printf(” %d”,a[i]);
}

int main()
{
int a[100],ch,pos,ITEM,i;

printf(“\n Enter the number of Elements: “);
scanf(“%d”,&n);

printf(“\n Enter the Elements: “);
for(i=0; i<n; i++)
scanf(“%d”,&a[i]);

do
{
printf(“\n ______________________________________ “);
printf(“\n MENU:\n”);
printf(“\n 1. Insert an element. “);
printf(“\n 2. Delete an element. “);
printf(“\n 3. Search for an element. “);
printf(“\n 4. Display elements. “);
printf(“\n 0. Exit. “);
printf(“\n Your Choice: “);
scanf(“%d”,&ch);

switch(ch)
{

case 1: //INSERT
printf(“\n Enter the Item to Insert: “);
scanf(“%d”,&ITEM);

SSort(a);
INS(a,ITEM);
Display(a);

break;

case 2: //DELETE
printf(“\n Enter the Item to Delete: “);
scanf(“%d”,&ITEM);

SSort(a);
DEL(a,ITEM);
Display(a);

break;

case 3: //SEARCH
printf(“\n Enter the Item to Search: “);
scanf(“%d”,&ITEM);

SSort(a);
pos=BSearch(a,ITEM);

if(pos==-1)
printf(“\n Item not Found. “);
else
printf(“\n Item found at %d position. “,pos+1);

break;

case 4: //DISPLAY
printf(“\n The Elements are: “);

SSort(a);
Display(a);

break;

case 0:
printf(“\n Exiting… “);
break;
}

}while(ch!=0);
getch();
}

 

 

Important Questions On Linked List :::


1) What pointer type is used to implement the heterogeneous linked list in C ?
Ans :

The answer is the void pointer.
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. Since we can’t use ordinary pointers for this, we use the void pointer. Void Pointer is a generic pointer type, and capable of storing pointer to any type.

2) Can we do a Binary Search on a LInked List ?
Ans :

We can get to the middle of the array just by saying array[middle].
Now, we cannot do the same with a linked list. We will have to write your own, possible inefficient algorithm to get the value of the middle node of a linked list. In a linked list, you lose the ability to get the value of any node in a constant time.

One solution to the inefficiency of getting the middle of the linked list during a binary search is to have the first node contain one additional pointer that points to he node in the middle. Decide at the first node if you need to check the first or the second half of the linked list. Continue doing that with each half list.

3) Whether Linked List is linear or Non Linear data structure ?

Ans :

According to Access strategies Linked LIst is a linear one.
According to Storage Linked List is a Non Linear One.

4) How can we search for data in a Linked List ?

Ans :

The only way to search a linked list is with a linear search, because the only way a linked list’s members cab be accessed is sequentially. Sometimes it is quicker to take the data from a linked list and store it in a different data structure so that searches can be more efficient.

5) What member function places a new node at the end of the Linked List ?

Ans:

The appendNode() member function places a new node at the end of the linked list. The appendNode() requires an integer representing the current data of the node.

6) What does the prototype of calloc() look like ?

Ans :  

void *calloc(size_t num, size_t size);

7) What is the lenth of the null() list ?

Ans :    1

Double Ended Queue ( DEQUE)


 

  It is a homogeneous list of elements in which insertion and deletion operations are performed from both the ends i.e, we can insert elements from the rear end or from the front ends. Hence, it is called double-ended queue. It is commonly referred to as deque.

There are two types of deques. These two types are due to the restrictions put to preform either the insertions or deletions only at the end. They are :

1) Input Restricted Deque
2) Output Restricted Deque

Four Operations :

=> Insertion of an element at the REAR end of the queue
=> Deletion of an element from the FRONT end of the queue
=> Insertion of an element at the FRONT end of the queue
=> Deletion of an element from the REAR end of the queue
For an input-restricted deque only the operations 1,2,3 & 4 are valid. And for an output-restricated deque only the operations specified in 1,2,3 are valid.

a) Insertion of an element at the REAR end of the queue

void dqinsert_rear(int q[10],int front,int rear,int item,int MAXSIZE)
{
if(rear == (MAXSIZE-1))
{
printf(” QUEUE is full “);
return;
}
rear=rear+1;
q[rear]=item;
}
b) Deletions of an element from the FRONT end of the queue

void dqdelete_front(int q[10],int front,int rear,int item)
{
if(front == rear)
{
printf(” QUEUE is empty “);
return;
}

front=front+1;
item=q[item];
}

3) Insertion of an element at the FRONT end of the queue

void dqinsert_front(int q[10], int front, int rear, int item)
{
if(front == 0)
{
printf(” QUEUE is full”);
return;
}
front=front-1;
q[front]=item;

}

d) Deletion of an element from the REAR end of the queue
void dqdelete_rear( int q[10], int front, int rear, int item)
{
if(front == rear)
{
printf(” QUEUE is empty “);
return;
}

rear=rear-1;
item=q[item];

}

e) Function to display the contents (status) of a QUEUE

void dq_display(int q[10], int front, int rear)
{
if(front <= rear)
{
printf(” Status of the Queue \n”);
for(i = front; i<=rear; i++)
printf(“%d”,dq[i]);

}
else
printf(” QUEUE is empty “);

}

C Program to print a linked list in reverse


#include<stdio.h>
#include<conio.h>

typedef struct linked_list
{
int item;
struct linked_list *next;
}node;

node *create_list();
void print_list(node *);
void print_list_in_reverse(node *);

int main()
{
node *head=NULL;

printf("you can create a list by entering elements press -999 to end\n");
head=create_list();
printf("\n The list is\n");
print_list(head);
printf("\n The list in reverse order is");
print_list_in_reverse(head);
printf("\n");
return 0;
}

node *create_list()
{
int x;
node *temp=NULL;
scanf("%d",&x);
if(x!=-999)
{
temp=(node*)malloc(sizeof(node));
temp->item=x;
temp->next=NULL;
temp->next=create_list();
}
return temp;
}
void print_list(node *p)
{
if(p)
{
printf("%d ",p->item);
print_list(p->next);
}
else
printf("\n");
}

void print_list_in_reverse(node *p)
{
if(p)
{
print_list_in_reverse(p->next);
printf("%d ",p->item);
}
else
printf("\n");
}

Search An Element in Linked List in C


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
                  {
                    int data;
                    struct node*next;
                  };
 void insert(struct node**p,int num)   /*Function for inserting an
element into a list */
 
 {
   if(*p==NULL)
     {
      (*p)=(struct node*)malloc(sizeof(struct node));
      (*p)->next=NULL;
      (*p)->data=num;
     }
   else
    {
     insert(&((*p)->next),num);
    }
 }
 
void display(struct node*p) /*Function for displaying the list*/
 {
   while(p!=NULL)
    {
     printf(“%d “,p->data);
     p=p->next;
    }
 }
 
 
void reverse(struct node**p) /*Function for reversing the list by
recursion */
 {
   struct node*q,*r,*x;
     int d;
     q=(*p);     /*stores the address of the first element */
     x=q;        /*also stores the element of the first element for
counter pourpose */
     d=q->data;  /*stores the data of the first element*/
     r=q->next;  /*stores the address of the second element in the list
*/
      free(q);   /*deletes the first element of the list*/
      if(x==NULL)
                return ;
                else
                  {
                    reverse(&(r));/*Recursive call*/
                    insert(p,d);  /*This function is put in the stack so the first
                                                     will be taken as last element for the new list */
                  }
 }
 
 void main()
 {
  clrscr();
  struct node*p=NULL;
  int n,d,i=0;
   printf(“How many…?”);
   scanf(“%d”,&n);
    while(i++!=n)
     {
      scanf(“%d”,&d);
      insert(&p,d);
     }
  display(p);
  reverse(&p);
  printf(“The reversed list is…”);
  display(p);
  getch();
 }

Prgram to insert & delete the elemnts from queue


#include<iostream.h>
 
#include<conio.h>
 
#include<stdlib.h>
 
 
 
class queue
 
{
 
    private:
 
        int i,r,q[25],front,rear;
 
    public:
 
        void enqueue(int);
 
        void dequeue();
 
        void getdata();
 
};
 
 
 
 
 
void queue::getdata()
 
{
 
    clrscr();
 
    cout<<endl<<“enter the=”” range=”” of=”” queue:”;=”” <br=””> cin>>r;
 
    cout<<endl<<“enter the=”” elments=”” of=”” queue:”;=”” <br=””>   for(i=0;i<r;i++) <br=””>    {
 
        cin>>q[i];
 
    }
 
    front=q[0];
 
    rear=q[2];
 
}
 
 
 
 
 
void queue::dequeue()
 
{
 
    int item;
 
    if(front==0)
 
    {
 
        cout<<endl<<“queue is=”” empty.”;=”” <br=””>     exit(0);
 
    }
 
    else
 
    {
 
        item=q[1];
 
    }
 
    if(front==rear)
 
    {
 
        front=0;
 
        rear=0;
 
    }
 
    else
 
    {
 
        front=front+1;
 
    }
 
 
 
    cout<<endl<<“after delection;”;=”” <br=””>
 
    for(i=0;i<r;i++) <br=””>    {
 
        cout<<“\t”<<q[i]; <br=””>  }
 
}
 
 
 
 
 
void queue::enqueue(int item)
 
{
 
    if(rear==r)
 
    {
 
        cout<<endl<<“queue is=”” full.”;=”” <br=””>      exit(0);
 
    }
 
    else
 
    {
 
        if(rear==0 && front==0)
 
        {
 
            front=1;
 
            rear=1;
 
        }
 
        r=r+1;
 
        q[r]=item;
 
    }
 
    cout<<endl<<“after insertion.”;=”” <br=””>   for(i=0;i<r+1;i++) <br=””>  {
 
        cout<<“\t”<<q[i]; <br=””>  }
 
}
 
 
 
 
 
void main()
 
{
 
    int ch,no;
 
    clrscr();
 
    char cho;
 
    queue q;
 
    q.getdata();
 
    cout<<endl<<endl<<“select the=”” operation=”” you=”” “;=”” <br=””>   cout<<“want to perform on queue:”;
 
    cout<<endl<<endl<<“1) insert”<<endl<<endl<<“2)=”” delete”;=”” <br=””>    cout<<endl<<endl<<“enter your=”” choice:”;=”” <br=””>    cin>>ch;
 
    do
 
    {
 
        switch(ch)
 
        {
 
            case 1:
 
                cout<<endl<<“enter the=”” number=”” which=”” you=”” want=”” to=”” insert:”;=”” <br=””>               cin>>no;
 
                q.enqueue(no);
 
                break;
 
            case 2:
 
                q.dequeue();
 
                break;
 
        }
 
    cout<<endl<<endl<<“do you=”” want=”” to=”” continue:”;=”” <br=””>    cin>>cho;
 
    }
 
    while(cho==’y’||cho==’Y’);
 
}

Sorting in descending order


 /* Bubble sort code */

#include<stdio.h>
main()
{
int array[100], n, c, d, swap;
printf(“Enter number of elements\n”);
scanf(“%d”,&n);
printf(“Enter %d integers\n”, n);
for( c =0; c < n ; c++)
scanf(“%d”,&array[c]);

for( c =0; c <( n -1); c++)
{
for( d =0; d < n – c -1; d++)
{
if( array[d]< array[d+1])
{
swap = array[d];
array[d]= array[d+1];
array[d+1]= swap;
}
}
}
printf(“Sorted list in descending order:\n”);
for( c =0; c < n ; c++)
printf(“%d\n”, array[c]);
return 0;
}

 

Data Structures XOR list example | XOR List Example in DS | Data Structures Program on XOR | XOR in Data Structure | C Program on XOR Data Structure



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

struct xnode {
int data;
unsigned long direction;
};

struct xnode *add_data(int data, struct xnode* list);
void walk_list(struct xnode *list);

int main(void) {

struct xnode *l2 = add_data(2, NULL);
struct xnode *l1 = add_data(1, l2);
struct xnode *l3 = add_data(3, l2);
struct xnode *l4 = add_data(4, l3);

printf("front -> back....\n");
walk_list(l1);
printf("back -> front....\n");
walk_list(l4);

return 0;
}

struct xnode *add_data(int data, struct xnode *list) {
struct xnode *newxnode = malloc(sizeof(struct xnode));

assert(newxnode);
newxnode->direction = (unsigned long)list;
newxnode->data = data;

if(list != NULL)
list->direction ^= (unsigned long)newxnode;

return newxnode;
}

void walk_list(struct xnode *list) {
unsigned long prev = 0;

while(list != NULL) {
unsigned long next = prev ^ list->direction;
printf("%d ", list->data);
prev = (unsigned long)list;
list = (struct xnode *)next;
}

printf("\n");
}

Tree Operations – INSERTION ,INORDER , PREORDER , POSTORDER TRAVERSAL in C | Data structure example on Tree Operation in C | C Assignments in Tree Sorting




# include< stdio.h>
# include < conio.h>
# include < malloc.h>

struct node
{
struct node *left;
int data;
struct node *right;
} ;

void main()
{
void insert(struct node **,int);
void inorder(struct node *);
void postorder(struct node *);
void preorder(struct node *);
struct node *ptr;
int will,i,num;
ptr = NULL;
ptr->data=NULL;
clrscr();

printf("
Enter the number of terms you want to add to the tree.
");
scanf("%d",&will);

/* Getting Input */
for(i=0;i
{
printf("
Enter the item");
scanf("%d",&num);
insert(&ptr,num);
}

getch();
printf("

INORDER TRAVERSAL

");
inorder(ptr);
getch();
printf("

PREORDER TRAVERSAL

");
preorder(ptr);
getch();
printf("

POSTORDER TRAVERSAL

");
postorder(ptr);
getch();
}



void insert(struct node **p,int num)
{


if((*p)==NULL)
{ printf("
Leaf node created.");
(*p)=malloc(sizeof(struct node));
(*p)->left = NULL;
(*p)->right = NULL;
(*p)->data = num;
return;
}
else
{ if(num==(*p)->data)
{
printf("

REPEATED ENTRY ERROR
VALUE REJECTED

");
return;
}
if(num<(*p)->data)
{
printf("
Directed to left link.");
insert(&((*p)->left),num);
}
else
{
printf("
Directed to right link.");
insert(&((*p)->right),num);
}
}
return;
}


void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("
Data :%d",p->data);
inorder(p->right);
}
else
return;
}


void preorder(struct node *p)
{
if(p!=NULL)
{
printf("
Data :%d",p->data);
preorder(p->left);
preorder(p->right);
}
else
return;
}


void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("
Data :%d",p->data);
}
else
return;
}

The Stack Data Structure in C and C++


The stack is a common data structure for representing things that need to maintained in a particular order. For instance, when a function calls another function, which in turn calls a third function, it’s important that the third function return back to the second function rather than the first.

One way to think about this implementation is to think of functions as being stacked on top of each other; the last one added to the stack is the first one taken off. In this way, the data structure itself enforces the proper order of calls.

Conceptually, a stack is simple: a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack. Consequently, a stack is said to have “first in last out” behavior (or “last in, first out”). The first item added to a stack will be the last item removed from a stack.

So what’s the big deal? Where do stacks come into play? As you’ve already seen, stacks are a useful way to organize our thoughts about how functions are called. In fact, the “call stack” is the term used for the list of functions either executing or waiting for other functions to return.

In a sense, stacks are part of the fundamental language of computer science. When you want to express an idea of the “first in last out” variety, it just makes sense to talk about it using the common terminology. Moreover, such operations show up an awful lot, from theoretical computer science tools such as a push-down automaton to AI, including implementations of depth-first search.

Stacks have some useful terminology associated with them:

  • Push To add an element to the stack
  • Pop To remove an element from the stock
  • Peek To look at elements in the stack without removing them
  • LIFO Refers to the last in, first out behavior of the stack
  • FILO Equivalent to LIFO

Lesson 18:Binary Trees in C



The binary tree is a fundamental data structure used in computer science. The binary tree is a useful data structure for rapidly storing sorted data and rapidly retrieving stored data. A binary tree is composed of parent nodes, or leaves, each of which stores data and also links to up to two other child nodes (leaves) which can be visualized spatially as below the first node with one placed to the left and with one placed to the right. It is the relationship between the leaves linked to and the linking leaf, also known as the parent node, which makes the binary tree such an efficient data structure. It is the leaf on the left which has a lesser key value (i.e., the value used to search for a leaf in the tree), and it is the leaf on the right which has an equal or greater key value. As a result, the leaves on the farthest left of the tree have the lowest values, whereas the leaves on the right of the tree have the greatest values. More importantly, as each leaf connects to two other leaves, it is the beginning of a new, smaller, binary tree. Due to this nature, it is possible to easily access and insert data in a binary tree using search and insert functions recursively called on successive leaves.

The typical graphical representation of a binary tree is essentially that of an upside down tree. It begins with a root node, which contains the original key value. The root node has two child nodes; each child node might have its own child nodes. Ideally, the tree would be structured so that it is a perfectly balanced tree, with each node having the same number of child nodes to its left and to its right. A perfectly balanced tree allows for the fastest average insertion of data or retrieval of data. The worst case scenario is a tree in which each node only has one child node, so it becomes as if it were a linked list in terms of speed. The typical representation of a binary tree looks like the following:

			
10
/ \
6 14
/ \ / \
5 8 11 18

The node storing the 10, represented here merely as 10, is the root node, linking to the left and right child nodes, with the left node storing a lower value than the parent node, and the node on the right storing a greater value than the parent node. Notice that if one removed the root node and the right child nodes, that the node storing the value 6 would be the equivalent a new, smaller, binary tree.
The structure of a binary tree makes the insertion and search functions simple to implement using recursion. In fact, the two insertion and search functions are also both very similar. To insert data into a binary tree involves a function searching for an unused node in the proper position in the tree in which to insert the key value. The insert function is generally a recursive function that continues moving down the levels of a binary tree until there is an unused leaf in a position which follows the rules of placing nodes. The rules are that a lower value should be to the left of the node, and a greater or equal value should be to the right. Following the rules, an insert function should check each node to see if it is empty, if so, it would insert the data to be stored along with the key value (in most implementations, an empty node will simply be a NULL pointer from a parent node, so the function would also have to create the node). If the node is filled already, the insert function should check to see if the key value to be inserted is less than the key value of the current node, and if so, the insert function should be recursively called on the left child node, or if the key value to be inserted is greater than or equal to the key value of the current node the insert function should be recursively called on the right child node. The search function works along a similar fashion. It should check to see if the key value of the current node is the value to be searched. If not, it should check to see if the value to be searched for is less than the value of the node, in which case it should be recursively called on the left child node, or if it is greater than the value of the node, it should be recursively called on the right child node. Of course, it is also necessary to check to ensure that the left or right child node actually exists before calling the function on the node.
Because binary trees have log (base 2) n layers, the average search time for a binary tree is log (base 2) n. To fill an entire binary tree, sorted, takes roughly log (base 2) n * n. Let’s take a look at the necessary code for a simple implementation of a binary tree. First, it is necessary to have a struct, or class, defined as a node.

struct node
{
int key_value;
struct node *left;
struct node *right;
};

The struct has the ability to store the key_value and contains the two child nodes which define the node as part of a tree. In fact, the node itself is very similar to the node in a linked list. A basic knowledge of the code for a linked list will be very helpful in understanding the techniques of binary trees. Essentially, pointers are necessary to allow the arbitrary creation of new nodes in the tree.

There are several important operations on binary trees, including inserting elements, searching for elements, removing elements, and deleting the tree. We’ll look at three of those four operations in this tutorial, leaving removing elements for later.

We’ll also need to keep track of the root node of the binary tree, which will give us access to the rest of the data:

struct node *root = 0;

It is necessary to initialize root to 0 for the other functions to be able to recognize that the tree does not yet exist. The destroy_tree shown below which will actually free all of the nodes of in the tree stored under the node leaf: tree.

void destroy_tree(struct node *leaf)
{
if( leaf != 0 )
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
free( leaf );
}
}

The function destroy_tree goes to the bottom of each part of the tree, that is, searching while there is a non-null node, deletes that leaf, and then it works its way back up. The function deletes the leftmost node, then the right child node from the leftmost node’s parent node, then it deletes the parent node, then works its way back to deleting the other child node of the parent of the node it just deleted, and it continues this deletion working its way up to the node of the tree upon which delete_tree was originally called. In the example tree above, the order of deletion of nodes would be 5 8 6 11 18 14 10. Note that it is necessary to delete all the child nodes to avoid wasting memory.

The following insert function will create a new tree if necessary; it relies on pointers to pointers in order to handle the case of a non-existent tree (the root pointing to NULL). In particular, by taking a pointer to a pointer, it is possible to allocate memory if the root pointer is NULL.

insert(int key, struct node **leaf)
{
if( *leaf == 0 )
{
*leaf = (struct node*) malloc( sizeof( struct node ) );
(*leaf)->key_value = key;
/* initialize the children to null */
(*leaf)->left = 0;
(*leaf)->right = 0;
}
else if(key < (*leaf)->key_value)
{
insert( key, &(*leaf)->left );
}
else if(key > (*leaf)->key_value)
{
insert( key, &(*leaf)->right );
}
}

The insert function searches, moving down the tree of children nodes, following the prescribed rules, left for a lower value to be inserted and right for a greater value, until it reaches a NULL node–an empty node–which it allocates memory for and initializes with the key value while setting the new node’s child node pointers to NULL. After creating the new node, the insert function will no longer call itself. Note, also, that if the element is already in the tree, it will not be added twice.

struct node *search(int key, struct node *leaf)
{
if( leaf != 0 )
{
if(key==leaf->key_value)
{
return leaf;
}
else if(key<leaf->key_value)
{
return search(key, leaf->left);
}
else
{
return search(key, leaf->right);
}
}
else return 0;
}

The search function shown above recursively moves down the tree until it either reaches a node with a key value equal to the value for which the function is searching or until the function reaches an uninitialized node, meaning that the value being searched for is not stored in the binary tree. It returns a pointer to the node to the previous instance of the function which called it. 

Lesson 15: Singly linked lists in C


Linked lists are a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Specifically, the programmer writes a struct definition that contains variables holding information about something and that has a pointer to a struct of its same type (it has to be a pointer–otherwise, every time an element was created, it would create a new element, infinitely). Each of these individual structs or classes in the list is commonly known as a node or element of the list.

One way to visualize a linked list is as though it were a train. The programmer always stores the first node of the list in a pointer he won’t lose access to. This would be the engine of the train. The pointer itself is the connector between cars of the train. Every time the train adds a car, it uses the connectors to add a new car. This is like a programmer using malloc to create a pointer to a new struct.

In memory a linked list is often described as looking like this:

 
---------- ----------
- Data - - Data -
---------- ----------
- Pointer- - - -> - Pointer-
---------- ----------

The representation isn’t completely accurate in all of its details, but it will suffice for our purposes. Each of the big blocks is a struct that has a pointer to another one. Remember that the pointer only stores the memory location of something–it is not that thing itself–so the arrow points to the next struct. At the end of the list, there is nothing for the pointer to point to, so it does not point to anything; it should be a null pointer or a dummy node to prevent the node from accidentally pointing to a random location in memory (which is very bad).

So far we know what the node struct should look like:

 
#include <stdlib.h>

struct node {
int x;
struct node *next;
};

int main()
{
/* This will be the unchanging first node */
struct node *root;

/* Now root points to a node struct */
root = malloc( sizeof(struct node) );

/* The node root points to has its next pointer equal to a null pointer
set */
root->next = 0;
/* By using the -> operator, you can modify what the node,
a pointer, (root in this case) points to. */
root->x = 5;
}

This so far is not very useful for doing anything. It is necessary to understand how to traverse (go through) the linked list before it really becomes useful. This will allow us to store some data in the list and later find it without knowing exactly where it is located.

Think back to the train. Let’s imagine a conductor who can only enter the train through the first car and can walk through the train down the line as long as the connector connects to another car. This is how the program will traverse the linked list. The conductor will be a pointer to node, and it will first point to root, and then, if the root’s pointer to the next node is pointing to something, the “conductor” (not a technical term) will be set to point to the next node. In this fashion, the list can be traversed. Now, as long as there is a pointer to something, the traversal will continue. Once it reaches a null pointer (or dummy node), meaning there are no more nodes (train cars) then it will be at the end of the list, and a new node can subsequently be added if so desired.

Here’s what that looks like:

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

struct node {
int x;
struct node *next;
};

int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;

root = malloc( sizeof(struct node) );
root->next = 0;
root->x = 12;
conductor = root;
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );

conductor = conductor->next;

if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->x = 42;

return 0;
}

That is the basic code for traversing a list. The if statement ensures that the memory was properly allocated before traversing the list. If the condition in the if statement evaluates to true, then it is okay to try and access the node pointed to by conductor. The while loop will continue as long as there is another pointer in the next. The conductor simply moves along. It changes what it points to by getting the address of conductor->next.

Finally, the code at the end can be used to add a new node to the end. Once the while loop as finished, the conductor will point to the last node in the array. (Remember the conductor of the train will move on until there is nothing to move on to? It works the same way in the while loop.) Therefore, conductor->next is set to null, so it is okay to allocate a new area of memory for it to point to (if it weren’t NULL, then storing something else in the pointer would cause us to lose the memory that it pointed to). When we allocate the memory, we do a quick check to ensure that we’re not out of memory, and then the conductor traverses one more element (like a train conductor moving on to the newly added car) and makes sure that it has its pointer to next set to 0 so that the list has an end. The 0 functions like a period; it means there is no more beyond. Finally, the new node has its x value set. (It can be set through user input. I simply wrote in the ‘=42’ as an example.)

To print a linked list, the traversal function is almost the same. In our first example, it is necessary to ensure that the last element is printed after the while loop terminates. (See if you can think of a better way before reading the second code example.)

For example:

 
conductor = root;
if ( conductor != 0 ) { /* Makes sure there is a place to start */
while ( conductor->next != 0 ) {
printf( "%d\n", conductor->x );
conductor = conductor->next;
}
printf( "%d\n", conductor->x );
}

The final output is necessary because the while loop will not run once it reaches the last node, but it will still be necessary to output the contents of the next node. Consequently, the last output deals with this. We can avoid this redundancy by allowing the conductor to walk off of the back of the train. Bad for the conductor (if it were a real person), but the code is simpler as it also allows us to remove the initial check for null (if root is null, then conductor will be immediately set to null and the loop will never begin):

 
conductor = root;
while ( conductor != NULL ) {
printf( "%d\n", conductor->x );
conductor = conductor->next;
}

Some Simple C Programs to a Bit Advanced



C > Small Programs sample source codes(WAV file player)

WAV file player

/WARNING: You need a HUGE memory model to run this.

#include “ALLOC.H”
#include “DOS.H”
#include “CONIO.H”
#include “STDIO.H”

void main()
{
char *name;
printf(“
Enter the file name…:”);
scanf(“%s”,name);

playwav(name,1.0);

}

void playwav(char wavefile[14],float delaytime);
struct WaveData {
unsigned int SoundLength, Frequency;
char *Sample;
};

struct HeaderType {
long RIFF; //RIFF header
char NI1 [18]; //not important

unsigned int Channels; //channels 1 = mono; 2 = stereo
long Frequency; //sample frequency
char NI2 [6]; //not important
char BitRes; //bit resolution 8/16 bit
char NI3 [12]; //not important
} Header;

struct WaveData Voice; //Pointer to wave file

unsigned int Base; //Sound Blaster base address

char WaveFile [25]; //File name for the wave file to be
played

/ Checks to see if a Sound Blaster exists at a given address, returns
true if Sound Blaster found, false if not.
/
int ResetDSP(unsigned int Test)
{
//Reset the DSP
outportb (Test + 0x6, 1);
delay(10);
outportb (Test + 0x6, 0);
delay(10);
//Check if (reset was succesfull
if ((inportb(Test + 0xE) & 0x80 == 0x80) && (inportb(Test + 0xA) ==
0xAA))
{
//DSP was found
Base = Test;
return (1);
}
else
//No DSP was found
return (0);
}

/ Send a byte to the DSP (Digital Signal Processor) on the Sound
Blaster
/
void WriteDSP(unsigned char Value)
{
//Wait for the DSP to be ready to accept data
while ((inportb(Base + 0xC) & 0x80) == 0x80);
//Send byte

outportb (Base + 0xC, Value);
}

/ Plays a part of the memory/

void PlayBack (struct WaveData *Wave)
{
long LinearAddress;
unsigned int Page, OffSet;
unsigned char TimeConstant;

TimeConstant = (65536 – (256000000 / Wave->Frequency)) >> 8;
WriteDSP(0x40); //DSP-command 40h – Set sample
frequency
WriteDSP(TimeConstant); //Write time constant

//Convert pointer to linear address
LinearAddress = FP_SEG (Wave->Sample);
LinearAddress = (LinearAddress << 4) + FP_OFF (Wave->Sample);
Page = LinearAddress >> 16; //Calculate page
OffSet = LinearAddress & 0xFFFF; //Calculate offset in the page
/*
Note – this procedure only works with DMA channel 1
*/
outportb (0x0A, 5); //Mask DMA channel 1
outportb (0x0C, 0); //Clear byte pointer
outportb (0x0B, 0x49); //Set mode
/*
The mode consists of the following:
0x49 = binary 01 00 10 01
| | | |
| | | +- DMA channel 01
| | +—- Read operation (the DSP reads from
memory)
| +——- Single cycle mode
+———- Block mode
*/

outportb (0x02, OffSet & 0x100); //Write the offset to the DMA
controller
outportb (0x02, OffSet >> 8);

outportb (0x83, Page); //Write the page to the DMA
controller

outportb (0x03, Wave->SoundLength & 0x100);
outportb (0x03, Wave->SoundLength >> 8);

outportb (0x0A, 1); //Unmask DMA channel

WriteDSP(0x14); // DSP-command 14h – Single cycle
playback
WriteDSP(Wave->SoundLength & 0xFF);
WriteDSP(Wave->SoundLength >> 8);
}

/ Loads a wave file into memory.
This procedure expects a _very_ standard wave header.
It doesn’t perform much error checking.
/
int LoadVoice (struct WaveData *Voice, char *FileName)
{
FILE *WAVFile;

//If it can’t be opened…
WAVFile = fopen(FileName, “rb”);
if (WAVFile == NULL) {
//..display error message

return (0);
}

//Return length of file for sound length minus 48 bytes for .WAV
header
fseek(WAVFile, 0L, SEEK_END);
Voice->SoundLength = ftell (WAVFile) – 48;
fseek(WAVFile, 0L, SEEK_SET);

//Check RIFF header
if (Voice->SoundLength > 32000) {

if (Voice->SoundLength > 64000) {

Voice->SoundLength = 64000;
}
}
free(Voice->Sample);
Voice->Sample = (char *)malloc(Voice->SoundLength); //Assign memory
if (!Voice->Sample) {

return (0);
}

//Load the sample data
fread(&Header, 46, 1, WAVFile);

//Check RIFF header
if (Header.RIFF != 0x46464952) {
printf (“Not a wave file
“);
return (0);
}

//Check channels
if (Header.Channels != 1) {
printf (“Not a mono wave file
“);
return (0);
}

//Check bit resolution
if (Header.BitRes != 8) {
printf (“Not an 8-bit wave file
“);
return (0);
}

Voice->Frequency = Header.Frequency;

//Load the sample data
fread(Voice->Sample, Voice->SoundLength + 2, 1, WAVFile);

fclose (WAVFile); //Close the file

return (1);
}

void playwav (char wavefile[14], float delaytime )
{
delaytime=1.0;
if (ResetDSP (0x220)) {
//at 220h
printf (“”);
} else {
if (ResetDSP (0x240)) {

//at 240h
printf (“”);
} else {
//or none at all
printf (“”);
return;
}
}

//Load wave file
if (LoadVoice (&Voice, wavefile)) {

//Start playback
PlayBack (&Voice);

delay(delaytime*1000);

//Stops DMA-transfer
WriteDSP (0xD0);
}
}

C > Small Programs sample source codes(Translate all DOT’S -056, except for the last one)

Translate all DOT’S -056, except for the last one

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

#define PACKAGE “dedot”
#define VERSION “1.0.0”
#define MAXLINE 1024

void print_help(int exval);

int main(int argc, char *argv[]) {
char line[MAXLINE];
char *ptr = NULL; /* points to the last dot */
char sub_char[1]; /* substidute char */
int sub_set = 0; /* substitude set ? */
int all_flag = 0; /* print all lines, even the ones not subject to change */
/* 1=on, 0=off */
int i = 0;
int opt;

while((opt = getopt(argc, argv, “hac:”)) != -1) {
switch(opt) {
case ‘h’:
print_help(0);
break;
case ‘a’:
all_flag = 1;
break;
case ‘c’:
sub_set = 1;
strncpy(sub_char, optarg, 1);
break;
case ‘:’:
fprintf(stderr, “%s: Option `%c’ needs an argument `-c CHAR’ ?\n\n”,
PACKAGE, optopt);
print_help(1);
break;
case ‘?’:
fprintf(stderr, “%s: No such option `%c’\n\n”, PACKAGE, optopt);
print_help(1);
break;
} /* switch */
} /* while */

while((fgets(line, 1024, stdin)) != NULL) {
if((ptr = strrchr(line, ‘.’)) == NULL) {
if(all_flag == 1)
printf(“%s”, line);

continue;
}

for(i = 0; i < strlen(line); i++)
if(sub_set == 1 && line[i] == ‘.’ && &line[i] != ptr)
printf(“%c”, sub_char[0]);
else if(line[i] != ‘.’ || &line[i] == ptr)
printf(“%c”, line[i]);
}

return 0;
}

void print_help(int exval) {
printf(“%s,%s remove every dot `.’ exept for the last one\n”, PACKAGE, VERSION);
printf(“%s [-h] [-c CHAR]\n\n”, PACKAGE);

printf(” -h print this help and exit\n”);
printf(” -c CHAR substitude all dots EXCEPT the last one with character `CHAR’\n”);
printf(” -a print all lines, even the ones which are not subject of change\n\n”);

exit(exval);
}

C > Small Programs sample source codes(The `Eta’ function)

The `Eta’ function

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

#define PACKAGE “eta”
#define VERSION “0.0.1”
#define MAXLINE 1024

/* status epilepticus, print help and exit with exval */
void print_help(int exval);
/* print program version and exit with exval */
void print_version(int exval);
/* `56′ `float’ detection ? */
/* returns -1 on error, 1 on `no dot’, 0 on `dot’ */
int is_float(char *val);

int main(int argc, char *argv[]) {
char line[MAXLINE]; /* fgets buff */
int overview_flag = 0; /* print overview only */
int count = 0; /* nr of input elements */
float total = 0; /* eta */
float num = 0; /* the actual element */
int opt = 0; /* parsed opt nr */
float highest = 0; /* the lowest encounterd nr */
float lowest = 0; /* the highest encounterd nr */

/* option parser */
while((opt = getopt(argc, argv, “hve”)) != -1) {
switch(opt) {
case ‘h’: /* print help and exit */
print_help(0);
case ‘v’: /* print version and exit */
print_version(0);
case ‘e’:
overview_flag = 1;
break;
case ‘?’:
fprintf(stderr, “%s: Error – No such option: `%c’\n\n”, PACKAGE, optopt);
print_help(1);
}
}

/* no remaining argumenst left ? read stdin() */
if((argc – optind) == 0) {
while((fgets(line, MAXLINE, stdin)) != NULL) {
/* strip newlines */
if(line[strlen(line) – 1] == ‘\n’)
line[strlen(line) – 1] = ”;

count++;
if(is_float(line) == 0)
num = atof(line);
else
num = atoi(line);

if(count == 1) highest = num, lowest = num;

if(num > highest) highest = num;
if(num < lowest) lowest = num; total += num; } } else { /* parse given elements as options */ /* just double the code .. 😉 */ for(; optind < argc; optind++) { count++; if(is_float(line) == 0) num = atoi(argv[optind]); else num = atof(argv[optind]); if(count == 1) highest = num, lowest = num; if(num > highest) highest = num;
if(num < lowest) lowest = num;
total += num;
}
}

if(overview_flag == 1) {
printf(“Nr of elements : %d\n”, count);
printf(“Sum of elements : %.2f\n”, total);
printf(“Average element : %.2f\n”, (total / count));
printf(“highest element : %.2f\n”, highest);
printf(“lowest element : %.2f\n”, lowest);
} else
printf(“%.2f\n”, (total / count));

return 0;
}

/* returns -1 on error, 1 on `no dot’, 0 on `dot’ */
int is_float(char *val) {
int retval = -1;

if(strchr(val, ‘.’) == NULL)
retval = 1;
else
retval = 0;

return retval;
}

/* status epilepticus, print help and exit with exval */
void print_help(int exval) {
printf(“%s,%s mathiCheesEcal `eta’ function\n”, PACKAGE, VERSION);
printf(“Usage: %s [-h] [-v] [-e] [[NUM1 NUM2 NUM3…]]\n\n”, PACKAGE);

printf(” -h print this help and exit\n”);
printf(” -v print version and exit\n”);
printf(” -e print a more complete overview of parsed input\n\n”);

exit(exval);
}

/* print program version and exit with exval */
void print_version(int exval) {

exit(exval);
}

C > Small Programs sample source codes(Quick hack convert M$ favorites to html list)

Quick hack convert M$ favorites to html list

#include < stdio.h>
#include < string.h>
#include < unistd.h>
#include < stdlib.h>
#include < dirent.h>
#include < sys/stat.h>

#define PACKAGE “forvavo”

/* recursion */
void recdir(char *dir);

int main(int argc, char *argv[]) {
 if(argc != 2)
  fprintf(stderr, “%s [directory]\n”, PACKAGE), exit(EXIT_FAILURE);
 else {
  printf(“\n”);
  printf(” \n”);
  printf(”  \n”);
  printf(” \n”);
  printf(“\n”);

  recdir(argv[1]);

  printf(“\n”);
  printf(“\n”);
 }

 return 0;
}

void recdir(char *dir) {
 DIR *dp;
 FILE *fp;
 char *ptr;
 char line[1024];
 struct dirent *entry;
 struct stat statbuf;

 if((dp = opendir(dir)) == NULL) {
  fprintf(stderr, “Cannot open directory: %s\n”, dir);
  return;
 }

 chdir(dir);
 while((entry = readdir(dp)) != NULL) {
  stat(entry->d_name, &statbuf);
  if(S_ISDIR(statbuf.st_mode)) {
   if(strcmp(“.”, entry->d_name) == 0 || strcmp(“..”, entry->d_name) == 0)
    continue;

   printf(“\n

%s

\n”, entry->d_name);
   printf(” 

C > Small Programs sample source codes(Print several types of alphabets)

Print several types of alphabets

#include < stdio.h>
#include < ctype.h>
#include < getopt.h>
#define PACKAGE “alphabet”
#define VERSION “0.0.5”
/*
// `0′ westeren,  `1′ phonetic, `2′ greek `3′ hebrew
// `4′ phoenician `5′ arab
*/
static int type = 0;
/* all output upper case */
static int upper = 0;
/* recursive, output until killed */
static int recur = 0;

/* phonetic alphabet */
const char *palpha[]= { “alpha”,   “bravo”,    “charlie”, “delta”,
                        “echo”,    “foxtrot”,  “golf”,    “hotel”,
                        “india”,   “juliet”,   “kilo”,    “lima”,
                        “mike”,    “november”, “oscar”,   “papa”,
                        “quebec”,  “romeo”,    “sierra”,  “tango”,
                        “uniform”, “victor”,   “whisky”,  “x-ray”,
                        “yankee”,  “zulu” };

/* lower case greek alphabet */
const char *galpha[]= { “alpha”,   “beta”,  “gamma”,   “delta”, 
                        “epsilon”, “zeta”,  “eta”,     “theta”,
                        “iota”,    “kappa”, “lambda”,  “mu”,
                        “nu”,      “xi”,    “omicron”, “pi”,   
                        “rho”,     “sigma”, “tau”,     “upsilon”,
                        “phi”,     “chi”,   “psi”,     “omega” };

/* lower case hebrew alphabet */
const char *halpha[]= { “tet”,  “chet”,   “zayin”, “vav”,
                        “he”,   “dalet”,  “gimel”, “bet”,
                        “alef”, “samech”, “nun”,   “nun”,
                        “mem”,  “mem”,    “lamed”, “khaf”,
                        “kaf”,  “yod”,    “tav”,   “shin”,
                        “resh”, “qof”,    “tzade”, “tzade”,
                        “fe”,   “pe”,     “ayin” };

/* lower case phoenician alphabet */
const char *nalpha[]= { “aleph”, “beth”,   “gimel”, “daleth”,
                        “he”,    “waw”,    “heth”,  “yodh”,
                        “kaph”,  “lamedh”, “mem”,   “nun”,
                        “ayin”,  “pe”,     “qoph”,  “resh”,
                        “sin”,   “taw”,    “waw”,   “samekh”,
                        “zayin” };

/* lower case arab alphabet */
const char *aalpha[]= { “xaa”,   “haa”,  “jiim”,  “th!aa”,
                        “taa”,   “baa”,  “alif”,  “saad”,
                        “shiin”, “siin”, “zaay”,  “raa”,
                        “thaal”, “daal”, “qaaf”,  “faa”,
                        “ghayn”, “ayn”,  “th:aa”, “taa”,
                        “daad”,  “yaa”,  “waaw”,  “haa”,
                        “nuun”,  “miim”, “laam”,  “kaaf” };

/* status epilepticus, and die with `exval’ */
void print_help(int exval);
/* print the specified alphabet */
void print_alphabet(void);

int main(int argc, char *argv[]) {
 int opt = 0;

 /* option parser */
 while((opt = getopt(argc, argv, “hvpgwiaru”)) != -1) {
  switch(opt) {
   case ‘h’: /* print help and exit */
    print_help(0);
   case ‘v’: /* print version and exit */
     exit(0);
   case ‘p’: /* print the phonetic alphabet */
    type = 1;
    break;
   case ‘g’: /* print the lower case greek alphabet */
    type = 2;
    break;
   case ‘w’: /* print the lower case hebrew alphabet */
    type = 3;
    break;
   case ‘i’: /* print the lower case phoenician alphabet */
    type = 4;
    break;
   case ‘a’: /* print the lower case arab alphabet */
    type = 5;
    break;
   case ‘r’: /* print the alphabet repeatedly until killed */
    recur = 1;
    break;
   case ‘u’: /* print all output upper case */
    upper = 1;
    break;
   case ‘?’: /* unkown option */
    fprintf(stderr, “%s: Error – no such option `%c’\n\n”, PACKAGE, optopt);
    print_help(1);
    break;
  } /* switch */
 } /* while */

 /* prints the selected alphabet */
 print_alphabet();

 return 0;
}

/* prints the selected alphabet */
void print_alphabet(void) {
 const char *ptr = NULL;
 int i = 0;

 /* western alphabet */
 if(type == 0) {
  if(upper == 0)
   for(i = 97; i <= 122; i++)
    printf(“%c\n”, i);
  else
   for(i = 65; i <= 90; i++)
    printf(“%c\n”, i);
 /* phonetic alphabet */
 } else if(type == 1) {
  if(upper == 0) {
   for(i = 0; i < 26; i++)
    printf(“%s\n”, palpha[i]);
  } else {
   for(i = 0; i < 26; i++) {
    ptr = palpha[i];
    while(*ptr)
     printf(“%c”, toupper(*ptr++));
    printf(“\n”);
   } /* for */
  } /* else */
 /* greek alphabet */
 } else if(type == 2) {
  if(upper == 0) {
   for(i = 0; i < 24; i++)
    printf(“%s\n”, galpha[i]);
  } else {
   for(i = 0; i < 24; i++) {
    ptr = galpha[i];
    while(*ptr)
     printf(“%c”, toupper(*ptr++));
    printf(“\n”);
   } /* for */
  } /* else */
 } else if(type == 3) {
  if(upper == 0) {
   for(i = 0; i < 27; i++)
    printf(“%s\n”, halpha[i]);
  } else {
   for(i = 0; i < 27; i++) {
    ptr = halpha[i];
    while(*ptr)
     printf(“%c”, toupper(*ptr++));
    printf(“\n”);
   } /* for */
  } /* else */
 } else if(type == 4) {
  if(upper == 0) {
   for(i = 0; i < 21; i++)
    printf(“%s\n”, nalpha[i]);
  } else {
   for(i = 0; i < 21; i++) {
    ptr = nalpha[i];
    while(*ptr)
     printf(“%c”, toupper(*ptr++));
    printf(“\n”);
   } /* for */
  } /* else */
 } else if(type == 5) {
  if(upper == 0) {
   for(i = 0; i < 28; i++)
    printf(“%s\n”, aalpha[i]);
  } else {
   for(i = 0; i < 28; i++) {
    ptr = aalpha[i];
    while(*ptr)
     printf(“%c”, toupper(*ptr++));
    printf(“\n”);
   } /* for */
  } /* else */
 } /* else if */

 if(recur == 1)
  print_alphabet();
 else
  return;
}

/* status epilepticus, and die with `exval’ */
void print_help(int exval) {
 printf(“%s,%s prints different alphabets\n”, PACKAGE, VERSION);
 printf(“Usage: %s [-h] [-v] [-p] [-g] [-w] [-i] [-a] [-r] [-u]\n\n”, PACKAGE);

 printf(” Startup:\n”);
 printf(”  -h    print this help and exit\n”);
 printf(”  -v    print version and exit\n\n”);

 printf(” Alphabet:\n”);
 printf(”  -p    print the phonetic alphabet\n”);
 printf(”  -g    print the greek alphabet\n”);
 printf(”  -w    print the hebrew alphabet\n”);
 printf(”  -i    print the phoenician alphabet\n”);
 printf(”  -a    print the arab alphabet\n\n”);

 printf(” Output:\n”);
 printf(”  -r    print the alphabet repeatedly until killed\n”);
 printf(”  -u    print all output in upper case\n\n”);

 printf(” Per default the Westeren alphabet is printed\n”);
 exit(exval);
}

C > Small Programs sample source codes(Print ip, email addressess or urls found in text)

Print ip, email addressess or urls found in text

#include < stdio.h>
#include < regex.h>
#include < ctype.h>
#include < getopt.h>
#include < stdlib.h>
#include < string.h>
#include < locale.h>
#include < sys/types.h>

#define PACKAGE    “miep”
#define VERSION    “1.0.0”

#define IPEXPR    “([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})”
#define EMEXPR    “.*@.*\\.([a-zA-Z]{1,3})$”
#define UREXPR    “(href|src)=”

void print_ipadd(FILE *fp);
void print_email(FILE *fp);
void print_url(FILE *fp);
void print_help(int exval);

int main(int argc, char *argv[]) {
 FILE *fp = stdin;
 int opt = 0;
 int em_set = 0;
 int ip_set = 0;
 int ur_set = 0;

 setlocale(LC_ALL, “”);

 while((opt = getopt(argc, argv, “hvieu”)) != -1) {
  switch(opt) {
   case ‘h’:
    print_help(0);
    break;
   case ‘v’:
    fprintf(stdout, “%s %s\n”, PACKAGE, VERSION);
    exit(0);
    break;
   case ‘i’:
    ip_set = 1;
    break;
   case ‘e’:
    em_set = 1;
    break;
   case ‘u’:
    ur_set = 1;
    break;
   case ‘?’:
    fprintf(stderr, “%s: Error: No such option `%c’\n\n”, PACKAGE, optopt);
    print_help(1);
    break;
  } /* switch */
 } /* while */

 if(argc == 1 || (ip_set == 0 && em_set == 0 && ur_set == 0))
  print_help(1);

 if((optind – argc) == 0) {
  if(em_set == 1)
   print_email(fp);
  else if(ip_set == 1)
   print_ipadd(fp);
  else
   print_url(fp);
 } else {
  /* loop over remaining args [files] */
  for(; optind < argc; optind++) {
   if(freopen(argv[optind], “r”, fp) == NULL) {
    perror(argv[optind]);
    continue;
   }

   if(em_set == 1)
    print_email(fp);
   else if(ip_set == 1)
    print_ipadd(fp);
   else
    print_url(fp);
  } /* for */
 } /* else */

 fclose(fp);
 return 0;
}

void print_ipadd(FILE *fp) {
 char line[1024];
 char *address = NULL;
 char delim[] = “,:;`/\”+-_(){}[]<>*&^%$#@!?~/|\\= \t\r\n”;
 int retval = 0;
 regex_t re;

 if(regcomp(&re, IPEXPR, REG_EXTENDED) != 0)
  return;

 while((fgets(line, 1024, fp)) != NULL) {
  if(strchr(line, ‘.’) == NULL)
   continue;

  address = strtok(line, delim);
  while(address != NULL) {
   if(strlen(address) <= 15)
    if((retval = regexec(&re, address, 0, NULL, 0)) == 0)
     printf(“%s\n”, address);

   address = strtok(NULL, delim);
  } /* while */
 } /* while */
} /* print_ipadd */

void print_email(FILE *fp) {
 char address[256];
 char line[1024];
 char *ptr1 = NULL;
 char *ptr2 = NULL;
 int retval = 0;
 regex_t re;

 if(regcomp(&re, EMEXPR, REG_EXTENDED) != 0)
  return;

 while((fgets(line, 1024, fp)) != NULL) {
  if(strchr(line, ‘@’) == NULL && strchr(line, ‘.’) == NULL)
   continue;

  for(ptr1 = line, ptr2 = address; *ptr1; ptr1++) {
   if(isalpha(*ptr1) || isdigit(*ptr1) || strchr(“.-_@”, *ptr1) != NULL)
    *ptr2++ = *ptr1;
   else {
    *ptr2 = ”;

    if(strlen(address) >= 6 && strchr(address, ‘@’) != NULL &&
       strchr(address, ‘.’) != NULL)
     if((retval = regexec(&re, address, 0, NULL, 0)) == 0)
      printf(“%s\n”, address);

    ptr2 = address;
   } /* else */
  } /* for */
 } /* while */
} /* print_email */

void print_url(FILE *fp) {
 char line[1024];
 char delim[] = “<> \t\n”;
 char *url = NULL;
 int retval = 0;
 regex_t re;

 if(regcomp(&re, UREXPR, REG_ICASE|REG_EXTENDED) != 0)
  return;

 while((fgets(line, 1024, fp)) != NULL) {
  url = strtok(line, delim);
  while(url != NULL) {
   if((retval = regexec(&re, url, 0, NULL, 0)) == 0)
    printf(“%s\n”, url);

   url = strtok(NULL, delim);
  } /* while */
 } /* while */
} /* print_url */

void print_help(int exval) {
 printf(“%s,%s print e-mail, urls or ip addresses from in textdata\n”, PACKAGE, VERSION);
 printf(“%s [-h] [-v] [-i] [-e] [-u] FILE…\n\n”, PACKAGE);

 printf(” -h        print this help and exit\n”);
 printf(” -v        print version and exit\n\n”);

 printf(” -i        print ip addresses\n”);
 printf(” -e        print e-mail addresses\n”);
 printf(” -u        print urls\n\n”);

 exit(exval);
}

C > Small Programs sample source codes(Positional notation of numbers)

Positional notation of numbers

#include < stdio.h>
#include < math.h>

#define PACKAGE “digits”

int number_of_digits(int x);
void print_help(void);

int main(int argc, char *argv[]) {
 int n;             /* input; the number to convert */
 short base;        /* input; base to which we will convert n */
 short rhdigit;     /* right-hand digit of n-prime */
 int power;         /* loop */

 if(argc != 3) {
  print_help();
  return 1;
 } else {
  sscanf(argv[1], “%d”, &n);
  if(n < 1) {
   fprintf(stderr, “%s: Error: Number must be greater than 0.\n”, PACKAGE);
   return 1;
  }

  sscanf(argv[2], “%hi”, &base);
  if(base < 2 || base > 10) {
   fprintf(stderr, “%s: Error: Base is not in required range.”, PACKAGE);
   return 1 ;
  }
 } /* else */

 printf(“The number %d, is %d wide, “, n, number_of_digits(n));
 printf(“and contains the numbers: “);

 /*
 // Generate digits of converted number, right to left.
 */
 for(power = 0; n != 0; power++) {
  rhdigit = n % base;         /* Isolate right-hand digit of n. */
  n /= base;                  /* then eliminate right-hand digit. */

  printf(“%hi “, rhdigit);
 }

 printf(“\n”);
 return 0;
}

int number_of_digits(int x) {
 return x ? (int)(log10((double)(abs(x))))+1 : 1;
}

void print_help(void) {
 fprintf(stdout, “Usage  : %s [NUMBER] [BASE]\n”, PACKAGE);
 fprintf(stdout, “Example: %s 4591 10\n”, PACKAGE);
}

C > Small Programs sample source codes(Pick random values)

Pick random values

#include < time.h>
#include < stdio.h>
#include < fcntl.h>
#include < string.h>
#include < stdlib.h>
#include < unistd.h>
#include < getopt.h>
#include < limits.h>
#include < sys/stat.h>
#include < sys/types.h>

#define PACKAGE “raval”
#define VERSION “0.0.1”

/* status epilepticus, print help and exit with `exval’ */
void print_help(int exval);
/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high);
/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void);

int main(int argc, char *argv[]) {
 int opt = 0;          /* holds option */
 int max = 10;         /* upper limit */
 int min = 0;          /* minimum limit */
 int many = 1;         /* the number of numbers to pick … */
 char *ptr = NULL;     /* separator for number range */

 while((opt = getopt(argc, argv, “hvn:r:”)) != -1) {
  switch(opt) {
   case ‘h’:
    print_help(0);
    break;
   case ‘v’:
   exit(0);
   case ‘n’:
    many = atoi(optarg);
    break;
   case ‘r’:
    if((ptr = strchr(optarg, ‘:’)) == NULL) {
     fprintf(stderr, “%s: Error – range `LOW:HIGH’\n\n”, PACKAGE);
     print_help(1);
    } else {
     ptr++, max = atoi(ptr);
     ptr–, ptr = ”;
     min = atoi(optarg);
     if(min >= max || min < 0 || max < 0) {
      fprintf(stderr, “%s: Error – range `LOW:HIGH’\n\n”, PACKAGE);
      print_help(1);
     }
    }
    break;
   case ‘?’:
    fprintf(stderr, “%s: Error – No such option: `%c’\n\n”, PACKAGE, optopt);
    print_help(1);
   case ‘:’:
    fprintf(stderr, “%s: Error – option `%c’ needs an argument\n\n”, PACKAGE, optopt);
    print_help(1);
  }
 }

 /* first seed the random function */
 srand((time_seed()));

 /* print the random values */
 for(; many > 0; many–)
  printf(“%4d\n”, get_rand_val(min, max));

 return 0;
}

/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high) {
 int k = 0;
 double d = 0;

 d = (double)rand() / ((double)RAND_MAX + 1);
 k = (int)(d * (high – low + 1));

 return(low + k);
}

/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void) {
 int retval = 0;
 int fd;

 /* just in case open() fails.. */
 if(open(“/dev/urandom”, O_RDONLY) == -1) {
  retval = (((int)time(NULL)) & ((1 << 30) – 1)) + getpid();
 } else {
  read(fd, &retval, 4);
  /* positive values only */
  retval = abs(retval) + getpid();
  close(fd);
 }

 return retval;
}

void print_help(int exval) {
 printf(“%s,%s print a random number\n”, PACKAGE, VERSION);
 printf(“Usage: %s OPTION…\n\n”, PACKAGE);

 printf(” -h         print this help and exit\n”);
 printf(” -v         print version and exit\n\n”);

 printf(” -n INT     return `INT’ numbers\n”);
 printf(” -r INT:INT keep the number within range `LOW:HIGH’,\n”);
 printf(”            default=(1:10)\n\n”);

 exit(exval);
}

C > Small Programs sample source codes(Pick and print a random value, line)

Pick and print a random value, line

#include < time.h>
#include < stdio.h>
#include < fcntl.h>
#include < string.h>
#include < stdlib.h>
#include < unistd.h>
#include < getopt.h>
#include < limits.h>
#include < sys/stat.h>
#include < sys/types.h>

#define PACKAGE “pand”
#define VERSION “0.0.3”
#define MAXLINE 1024

/* status epilepticus, print help and exit with `exval’ */
void print_help(int exval);
/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high);
/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void);

int main(int argc, char *argv[]) {
 int i = 0;                   /* generic counter */
 int len = 0;                 /* line length */
 int opt = 0;                 /* holds the parsed option nr */
 int pick = 0;                /* holds the random pick number */
 int exval = 0;               /* exit code for program */
 int verbose = 0;             /* work verbose … */
 int outputnum = 1;           /* number of random lines to output, default = 1 */
 int linecount = 0;           /* line counter */
 int maxlsize = -1;           /* do not include lines shorter as maxlsize */
 FILE *fp = NULL;             /* filestream pointer */
 char line[MAXLINE];          /* line buffer */
 char **strarray = NULL;      /* the string array which holds all the lines */

 /* no options given ? */
 if(argc == 1)
  print_help(0);

 while((opt = getopt(argc, argv, “hVvl:n:”)) != -1) {
  switch(opt) {
   case ‘h’: /* status epilepticus, print help and exit with `exval’ */
    print_help(0);
    break;
   case ‘V’: /* print version information and exit */
    exit(0);
    break;
   case ‘v’:
    verbose = 1;
    break;
   case ‘l’: /* only index lines longer as `maxlsize’ */
    maxlsize = atoi(optarg);
    break;
   case ‘n’: /* number of random lines to output default = 1 */
    outputnum = atoi(optarg);
    break;
   case ‘?’: /* unkown option */
    fprintf(stderr, “%s: Error – no such option `%c’\n\n”, PACKAGE, optopt);
    print_help(1);
    break;
   case ‘:’: /* option requires an argument */
    fprintf(stderr, “%s: Error – option `%c’ requires an argument\n\n”, PACKAGE,
      optopt);
    print_help(1);
    break;
  } /* switch */
 } /* while */

 /* no input arguments [files] left ? */
 if((argc – optind) == 0) {
  fprintf(stderr, “%s: Error – No input files given…\n\n”, PACKAGE);
  print_help(1);
 }

 /* first seed the random function */
 srand((time_seed()));

 /* loop over all input files */
 for(; optind < argc; optind++) {
  if((fp = fopen(argv[optind], “r”)) == NULL) {
   perror(argv[optind]);
   exval = 1;
   continue;
  }
  if(verbose == 1)
   printf(“%s: reading file `%s’\n”, PACKAGE, argv[optind]);

  /* read lines */
  while((fgets(line, MAXLINE, fp)) != NULL) {
   len = strlen(line);
   /* if max size… ignore line */
   if(maxlsize != -1 && len < maxlsize)
    continue;

   /* strip trailing newline */
   if(line[len – 1] == ‘\n’)
    line[len – 1] = ”;

   /* add the line, to the array of strings */
   strarray = (char **)realloc(strarray, (linecount + 1) * sizeof(char *));
   strarray[linecount++] = strdup(line);
  } /* while */

  if(verbose == 1)
   printf(“%s: array length now `%d’\n”, PACKAGE, linecount);

  fclose(fp);
 } /* for */

 /* output INT number of lines; (default=1) */
 for(; outputnum > 0; outputnum–) {
  /* is the array actually filled up with entrys ? */
  if(linecount <= 1) {
   exval = 2;
   break;
  } else {
   /* pick a random value */
   pick = get_rand_val(1, linecount);
   /* print the entry */
   if(verbose == 1)
    printf(“%s: %2d %s\n”, PACKAGE, pick, strarray[pick]);
   else
    printf(“%s\n”, strarray[pick]);
  }
 } /* for */

 /* free each entry */
 for(i = 0; i < linecount; i++)
  free(strarray[i]);

 /* free the string array */
 free(strarray);

 if(verbose == 1) {
  if(exval == 1)
   printf(“%s: Error – exit value `1’\n”, PACKAGE);
  else if(exval == 2)
   printf(“%s: Error – exit value `2′, not enough input…\n”, PACKAGE);
  else
   printf(“%s: normal exit value `0’\n”, PACKAGE);
 }

 return exval;
} /* end main */

/* picks a radom value withing range low-high*/
int get_rand_val(int low, int high) {
 int k = 0;
 double d = 0;

 d = (double)rand() / ((double)RAND_MAX + 1);
 k = (int)(d * (high – low + 1));

 return(low + k);
}

/* ! definitely not cryptographic secure ! */
/* value returned seeds the rand() function */
unsigned time_seed(void) {
 int retval = 0;
 int fd;

 /* just in case open() fails.. */
 if(open(“/dev/urandom”, O_RDONLY) == -1) {
  retval = (((int)time(NULL)) & ((1 << 30) – 1)) + getpid();
 } else {
  read(fd, &retval, 4);
  /* positive values only */
  retval = abs(retval) + getpid();
  close(fd);
 }

 return retval;
}

/* status epilepticus, print help and exit with `exval’ */
void print_help(int exval) {
 printf(“%s,%s pick random values from a file\n”, PACKAGE, VERSION);
 printf(“Usage: %s [-h] [-V] [-v] [-l INT] [-n INT] FILE1 FILE2…\n\n”, PACKAGE);

 printf(” Options:\n”);
 printf(”  -h        print this help and exit\n”);
 printf(”  -V        print version and exit\n”);
 printf(”  -v        work verbose\n”);
 printf(”  -l INT    pick only lines longer as `INT’ characters\n”);
 printf(”  -n INT    pick `INT’ random lines from input (default=1)\n\n”);

 printf(” Note: %s reads all input into memory first, and\n”, PACKAGE);
 printf(” only then picks a random entry from the memory.\n\n”);

 exit(exval);
}

C > Small Programs sample source codes(Parse custom httpd log)

Parse custom httpd log

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

struct tnode {
 char *string;
 int count;
 struct tnode *left, *right;
};

/* total nr. of nodes */
static int tnodecount = 0;

struct tnode *addtree(struct tnode *, char *);
void freetree(struct tnode *);
void freetarr(struct tnode **);
char *strdup(const char *s);
int tree_to_array(struct tnode **, struct tnode *);
int cmpr(const void *x, const void *y);

int main(void) {
 FILE *fp = stdin;
 struct tnode *root = {0};
 struct tnode **tnarray = {0};
 char line[1024];
 char *start = NULL;
 char *end   = NULL;
 char *filename = NULL;
 int i = 0;

 /* get unresponsibly wild with pointers */
 while(fgets(line, 1024, fp) != NULL) {
  if((start = strchr(line, ‘”‘)) == NULL)
   continue;

  start++;
  for(end = start; *end; end++) {
   if(*end == ‘”‘)
    break;
  }
  *end = ”;
  if((filename = strchr(start, ‘ ‘)) == NULL)
   continue;

  filename += 2;
  end = strrchr(filename, ‘ ‘);
  *end = ”;

  /* grow a tree for world peace */
  root = addtree(root, filename);
 }

 /* allocate mem for ptr array */
 tnarray = malloc(tnodecount * sizeof(*tnarray));
 /* read btree into array */
 tree_to_array(tnarray, root);
 /* qsort the array */
 qsort(tnarray, tnodecount, sizeof(*tnarray), cmpr);

 /* print the result */
 for(i = 0; i < tnodecount; i++)
  printf(“%4d %s\n”, tnarray[i]->count, tnarray[i]->string);

 /* clean up mess, mom’s proud.. */
 freetree(root);
 freetarr(tnarray);
 fclose(fp);

 return 0;
}

struct tnode *addtree(struct tnode *p, char *w) {
 int cond;

 if(p == NULL) {
  p = (struct tnode *)malloc(sizeof(struct tnode));
  p->string = strdup(w);
  p->count = 1;
  p->left = p->right = NULL;
  tnodecount++;
 } else if((cond = strcmp(w, p->string)) == 0)
  p->count++;
 else if(cond < 0)
  p->left = addtree(p->left, w);
 else
  p->right = addtree(p->right, w);

 return p;
}

void freetree(struct tnode *p) {
 if(p != NULL) {
  freetree(p->left);
  freetree(p->right);
  free(p->string);
  free(p);
 }
}

void freetarr(struct tnode **p) {
 int i = 0;

 if(p != NULL)
  for(i = 0; i < tnodecount; i++)
   free(p);
}

char *strdup(const char *s) {
 char *result = malloc(strlen(s) + 1);

 if(result == NULL)
  return NULL;

 strcpy(result, s);
 return result;
}

int tree_to_array(struct tnode **array, struct tnode *tree) {
 static struct tnode **write = NULL;

 if(tree == NULL)
  return -1;

 if(array != NULL)
  write = array;

 if(tree != NULL) {
  *write = tree, write++;
  if(tree->left != NULL)
   tree_to_array(NULL, tree->left);
  if(tree->right != NULL)
   tree_to_array(NULL, tree->right);
 }

 return 0;
}

int cmpr(const void *x, const void *y) {
 struct tnode * const *a = x;
 struct tnode * const *b = y;
 int retval = 0;

 if(a == NULL || b == NULL)
  return -2;

 if((*a)->count > (*b)->count)
  retval = -1;
 else if((*a)->count < (*b)->count)
  retval = 1;
 else
  retval = 0;

 return retval;
}

C > Small Programs sample source codes(Get color and coordinates for each pixel)

Get color and coordinates for each pixel

#include < stdio.h>
#include < gd.h>

int main(int argc, char *argv[]) {
 FILE *fp = {0};
 gdImagePtr img;
 int x = 0;
 int y = 0;
 int width = 0;
 int height = 0;

 if(argc != 2) {
  fprintf(stderr, “Usage: gixel image.png\n”);
  return 1;
 }

 fp = fopen(argv[1], “rb”);
 if(fp == NULL) {
  fprintf(stderr, “Error – fopen(%s)\n”, argv[1]);
  return 1;
 }

 img = gdImageCreateFromPng(fp);
 fclose(fp);

 width = gdImageSX(img);
 height = gdImageSY(img);

 for(x = 0; x < width; x++)
  for(y = 0; y < height; y++)
   printf(“%d,%d:%X\n”, x, y, gdImageGetPixel(img, x, y));

 gdImageDestroy(img);
 return 0;
}

C > Small Programs sample source codes(Generate a color palette)

Generate a color palette

#include < stdio.h>
#include < error.h>
#include < math.h>
#include < gd.h>

#define RGB2INT(r,g,b)  (b + 256 * g + 256 * 256 * r)

int main(int argc, char *argv[]) {
 FILE *fp = {0};
 gdImagePtr img = {0};
 char *fname = NULL;
 int x, y, w, h, color;
 int red, green, blue;
 int palette[256] = {0};

 if(argc != 2)
  error(1, 0, “Usage: gdpalette image.png”);
 else
  fname = argv[1];

 w = 256, h = 100;
 img = gdImageCreateTrueColor(w, h);

 for(x = 0; x < 256; x++) {
  red   = (int)(128.0 + 128 * sin(3.1415 * x / 16.0));
  green = (int)(128.0 + 128 * sin(3.1415 * x / 32.0));
  blue  = (int)(128.0 + 128 * sin(3.1415 * x / 64.0));
  palette[x] = RGB2INT(red, green, blue);
 }

 for(x = 0; x < w; x++)
  for(y = 0; y < h; y++) {
   red   = gdImageRed(img, palette[x]);
   green = gdImageGreen(img, palette[x]);
   blue  = gdImageBlue(img, palette[x]);
   color = gdImageColorAllocate(img, red, green, blue);
   gdImageSetPixel(img, x, y, color);
  }

 if((fp = fopen(fname, “w”)) == NULL)
  error(1, 0, “Error – fopen(): %s”, fname);
 else {
  gdImagePng(img, fp);
  fclose(fp);
 }

 gdImageDestroy(img);
 return 0;
}

C > Small Programs sample source codes(Folder Protection Software)

Folder Protection Software

#include< stdio.h>
#include< string.h>
#include< process.h>
void main()
{
FILE *p;
char ch,s[100];
char r[100]=”REN “;

char u[]=”.{21EC2020-3AEA-1069-A2DD-08002B30309D} “;
char v[50];
int choice,i;

clrscr();
p=fopen(“C:\a.bat”,”w+”);
if(p==NULL)
{
printf(“
Error in opening the file a.c
“);
exit(0);
}

printf(“

This software can convert your File/Folder to Control
Panel
and can Restore again.”);
printf(“
Enter the path of the file
“);
fflush(stdin);
gets(s);

for(i=0;i<25;i++)
fputs(“echo This software is not responsible for any loss in
data
“,p);

printf(“
Enter choice :”);
printf(“
1.Protect Folder/File”);
printf(“
2.Unprotect folder/File”);
printf(“
3.Exit
“);
scanf(“%d”,&choice);

switch(choice)
{
case 1:
       strcat(r,s);

       printf(“
Enter new name of your folder/file
“);
       fflush(stdin);
       gets(v);
       strcat(r,” “);
       strcat(r,v);
       strcat(r,u);
       break;
case 2:
       strcat(r,s);
       strcat(r,u);
       printf(“
Enter new name of your folder/file
“);
       fflush(stdin);
       gets(v);
       strcat(r,v);
       break;
default:
     fclose(p);
     remove(“C:\a.bat”);

     exit(0);
}

{
fputs(r,p);
for(i=0;i<25;i++)
fputs(“
echo This software is not responsible for any loss in data
“,p);
fputs(“
exit”,p);

}

fclose(p);

system(“C:\a.bat”);

remove(“C:\a.bat”);

}

C > Small Programs sample source codes(Filter text with a stop word list)

Filter text with a stop word list

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

#define MAXTOKENS       256
#define MAXLINE         1024
#define MINLEN          3
#define STMINLEN        2

struct tnode {
 char *word;
 int count;
 struct tnode *left, *right;
};

struct tnode *buildstoptree(char *, struct tnode *);
struct tnode *addtree(struct tnode *, char *);
struct tnode *findstopword(struct tnode *, char *);
struct tnode *talloc(void);
void freetree(struct tnode *);
char **split(char *, char *);

int main(int argc, char *argv[]) {
 /* delim does not include \’ [47] quote */
 char *delim = “.,:;`\”+-_(){}[]<>*&^%$#@!?~/|\\= \t\r\n1234567890”;
 char **tokens = NULL;
 struct tnode *root = {0};
 struct tnode *querry = {0};
 char line[MAXLINE];
 int i = 0;

 if(argc != 2) {
  fprintf(stderr, “Usage: tokstop STOPLIST.txt\n”);
  return 1;
 }

 root = buildstoptree(argv[1], root);
 if(root == NULL)
  return 1;

 while(fgets(line, MAXLINE, stdin) != NULL) {
  if(strlen(line) < MINLEN)
   continue;

  tokens = split(line, delim);
  for(i = 0; tokens[i] != NULL; i++) {
   querry = findstopword(root, tokens[i]);
   if(querry == NULL)
    printf(“%s “, tokens[i]);
  }

  for(i = 0; tokens[i] != NULL; i++)
   free(tokens[i]);
  free(tokens[i]);
  printf(“\n”);
 }

 freetree(root);
 return 0;
}

/* read stoplist into binary tree, expects one entry per line */
struct tnode *buildstoptree(char *fname, struct tnode *p) {
 FILE *fp = {0};
 char line[MAXLINE];
 int len = 0, lcount = 0;

 fp = fopen(fname, “r”);
 if(fp == NULL) {
  fprintf(stderr, “Error – fopen(%s)\n”, fname);
  return NULL;
 }

 while(fgets(line, MAXLINE, fp) != NULL) {
  len = strlen(line);
  if(len < STMINLEN)
   continue;
  else
   lcount++;

  if(line[len – 1] == ‘\n’)
   line[–len] = ”;

  p = addtree(p, line);
 }

 if(lcount == 0) {
  fprintf(stderr, “Error – Zero stopwords..\n”);
  return NULL;
 }

 fclose(fp);
 return p;
}

/* split string into tokens, return token array */
char **split(char *string, char *delim) {
 char **tokens = NULL;
 char *working = NULL;
 char *token = NULL;
 int idx = 0;

 tokens  = malloc(sizeof(char *) * MAXTOKENS);
 if(tokens == NULL)
  return NULL;
 working = malloc(sizeof(char) * strlen(string) + 1);
 if(working == NULL)
  return NULL;

 /* to make sure, copy string to a safe place */
 strcpy(working, string);
 for(idx = 0; idx < MAXTOKENS; idx++)
  tokens[idx] = NULL;

 token = strtok(working, delim);
 idx = 0;

 /* always keep the last entry NULL terminated */
 while((idx < (MAXTOKENS – 1)) && (token != NULL)) {
  tokens[idx] = malloc(sizeof(char) * strlen(token) + 1);
  if(tokens[idx] != NULL) {
   strcpy(tokens[idx], token);
   idx++;
   token = strtok(NULL, delim);
  }
 }

 free(working);
 return tokens;
}

/* install word in binary tree */
struct tnode *addtree(struct tnode *p, char *w) {
 int cond;

 if(p == NULL) {
  p = talloc();
  p->word = strdup(w);
  p->count = 1;
  p->left = p->right = NULL;
 } else if((cond = strcmp(w, p->word)) == 0)
  p->count++;
 else if(cond < 0)
  p->left = addtree(p->left, w);
 else
  p->right = addtree(p->right, w);

 return p;
}

/* make new tnode */
struct tnode *talloc(void) {
 return(struct tnode *)malloc(sizeof(struct tnode));
}

/* find value w in binary tree */
struct tnode *findstopword(struct tnode *p, char *w) {
 struct tnode *temp;
 int cond = 0;

 temp = p;

 while(temp != NULL) {
  if((cond = strcmp(temp->word, w)) == 0)
   return temp;
  else if(cond > 0)
   temp = temp->left;
  else
   temp = temp->right;
 }

 return NULL;
}

/* free binary tree */
void freetree(struct tnode *p) {
 if(p != NULL) {
  free(p->left);
  free(p->right);

  free(p->word);
  free(p);
 }
}

C > Small Programs sample source codes( Extract character ngrams from textdata)

Extract character ngrams from textdata

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

#define MAXLINE         1024
#define MINLEN          3

/* print all ngrams for `str’ */
void printgrams(char *, int);
/* padd token to, one prefix, and (N – 1) affix */
char *mkpadgr(char *, char *, int);

int main(int argc, char *argv[]) {
 char *delim = “.,:;`’\”+-_(){}[]<>*&^%$#@!?~/|\\= \t\r\n1234567890”;
 char *token = NULL;
 char line[MAXLINE];
 int nglen, i;

 i = nglen = 0;

 if(argc != 2) {
  fprintf(stderr, “Usage: chargram INT\n”);
  return 1;
 } else
  nglen = atoi(argv[1]);

 while(fgets(line, MAXLINE, stdin) != NULL) {
  if(strlen(line) < MINLEN)
   continue;

  token = strtok(line, delim);
  while(token != NULL) {
   printgrams(token, nglen);
   token = strtok(NULL, delim);
  }
 }

 return 0;
}

/* print all ngrams for `str’ */
void printgrams(char *str, int N) {
 char *padded = NULL;
 char *gram = NULL;
 int i = 0, j = 0;

 padded = mkpadgr(str, “_”, N);

 for(i = 0; i < strlen(str) + 1; i++) {
  gram = &padded[i];
  for(j = 0; j < N; j++) {
   printf(“%c”, gram[j]);
  }
  printf(“\n”);
 }

 free(padded);
 return;
}

/* padd word according to one prefix, and (N – 1) affix */
char *mkpadgr(char *str, char *padd, int N) {
 char *buff = NULL;
 int i = 0;

 buff = calloc(strlen(str) + 2 + (N – 1), sizeof(char));
 strcat(buff, padd), strcat(buff, str);
 for(i = 0; i < (N – 1); i++)
  strcat(buff, padd);

 return buff;
}

C > Small Programs sample source codes( Extract [word]grams from textdata)

Extract [word]grams from textdata

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

#define PACKAGE “wgram”
#define VERSION “0.0.4”
#define MAXLINE 1024
#define MAXGRAM 32

/* status epilepticus .. print help */
void print_help(int exval);

int main (int argc, char *argv[]) {
 /* word delimeter for strtok() */
 char delim[] = “.,:;`/\”+-_(){}[]<>*&^%$#@!?~/|\\=1234567890 \t\n”;
 char line[MAXLINE];     /* input buff, fgets() */
 char *stray = NULL;     /* returned value by strtok() */
 char **strarray = NULL; /* array to hold all entrys */
 int i = 0;              /* general counter */
 int strcount = 0;       /* number of entrys in pointer array */
 int N = 3, pos = 0;     /* ngram size, 3 in this case */
 int opt = 0;            /* holds command line opt nr.. */
 int word_flag = 0;      /* print only the `raw’ words */
 FILE *fp = stdin;       /* read input from `FILE’, default is stdin */

 while((opt = getopt(argc, argv, “hvn:wf:”)) != -1) {
  switch(opt) {
   case ‘h’:
    print_help(0);
    break;
   case ‘v’:
  exit(0);
    break;
   case ‘n’:
    N = atoi(optarg);
    if(N > MAXGRAM || N < 2) {
     fprintf(stderr, “%s: Error – Ngram length `%d’ out of range `0-%d’\n”,
       PACKAGE, N, MAXGRAM);
     return 1;
    }
    break;
   case ‘w’:
    word_flag = 1;
    break;
   case ‘f’:
    if(freopen(optarg, “r”, fp) == NULL) {
     fprintf(stderr, “%s: Error – opening `%s’\n”, PACKAGE, optarg);
     return 1;
    }
    break;
   case ‘?’:
    fprintf(stderr, “%s: Error – No such option: `%c’\n\n”, PACKAGE, optopt);
    print_help(1);
  } /* switch */
 } /* while */

 /* start reading lines from file pointer, add all entrys to **strarray */
 while((fgets(line, MAXLINE, fp)) != NULL) {
  if(strlen(line) < 2)
   continue;

  stray = strtok(line, delim);
  while(stray != NULL) {
   strarray = (char **)realloc(strarray, (strcount + 1) * sizeof(char *));
   strarray[strcount++] = strdup(stray);
   stray = strtok(NULL, delim);
  }
 }

 if(word_flag == 0) {
  /*
  // print the array of strings, jumping back each time
  // (N – 1) positions if a whole ngram of words has been printed
  */
  for(i = 0, pos = N; i < strcount; i++, pos–) {
   if(pos == 0) pos = N, i -= (N – 1), printf(“\n”);
    printf(“%s “, strarray[i]);
  }
  printf(“\n”);
 } else {
  /* print raw words */
  for(i = 0; i < strcount; i++)
   printf(“%s\n”, strarray[i]);
 }

 /* free the string array */
 for(i = 0; i < strcount; i++)
  free(strarray[i]);

 free(strarray);
 return 0;
}

/* status epilepticus .. print help */
void print_help(int exval) {
 printf(“%s,%s extract N-grams from text data\n”, PACKAGE, VERSION);
 printf(“Usage: %s [-h] [-v] [-n INT] [-w] [-f FILE]\n\n”, PACKAGE);

 printf(” -h        print this help and exit\n”);
 printf(” -v        print version and exit\n\n”);

 printf(” -n INT    set ngram length (default=3)\n”);
 printf(” -w        print only the extracted words\n”);
 printf(” -f FILE   read input from `FILE’ (default=stdin)\n\n”);
 exit(exval);
}

C > Small Programs sample source codes( Display +200 colors, rgb values, their hex equivalents and names)

Display +200 colors, rgb values, their hex equivalents and names

#include < stdio.h>

#define TOTAL_COLORS   12

struct colour {
 char name[28];
 int red;
 int green;
 int blue;
};

struct colour whitetab[] = {
 { “antique white”,       250, 235, 215 },
 { “azure”,               240, 255, 255 },
 { “bisque”,              255, 228, 196 },
 { “blanched almond”,     255, 235, 205 },
 { “cornsilk”,            255, 248, 220 },
 { “eggshell”,            252, 230, 201 },
 { “floral white”,        255, 250, 240 },
 { “gainsboro”,           220, 220, 220 },
 { “ghost white”,         248, 248, 255 },
 { “honeydew”,            240, 255, 240 },
 { “ivory”,               255, 255, 240 },
 { “lavender”,            230, 230, 250 },
 { “lavender blush”,      255, 240, 245 },
 { “lemon chiffon”,       255, 250, 205 },
 { “linen”,               250, 240, 230 },
 { “mint cream”,          245, 255, 250 },
 { “misty rose”,          255, 228, 225 },
 { “moccasin”,            255, 228, 181 },
 { “navajo white”,        255, 222, 173 },
 { “old lace”,            253, 245, 230 },
 { “papaya whip”,         255, 239, 213 },
 { “peach puff”,          255, 218, 185 },
 { “seashell”,            255, 245, 238 },
 { “snow”,                255, 250, 250 },
 { “thistle”,             216, 191, 216 },
 { “titanium white”,      252, 255, 240 },
 { “wheat”,               245, 222, 179 },
 { “white”,               255, 255, 255 },
 { “white smoke”,         245, 245, 245 },
 { “zinc white”,          253, 248, 255 }
};

struct colour greytab[] = {
 { “cold grey”,           128, 138, 135 },
 { “dim grey”,            105, 105, 105 },
 { “grey”,                192, 192, 192 },
 { “light grey”,          211, 211, 211 },
 { “slate grey”,          112, 128, 144 },
 { “slate grey dark”,      47,  79,  79 },
 { “slate grey light”,    119, 136, 153 },
 { “warm grey”,           128, 128, 105 }
};

struct colour blacktab[] = {
 { “black”,       0,  0,  0  },
 { “ivory black”, 41, 36, 33 },
 { “lamp black”,  46, 71, 59 }
};

struct colour redtab[] = {
 { “alizarin crimson”,    227,  38,  54 },
 { “brick”,               156, 102,  31 },
 { “cadmium red deep”,    227,  23,  13 },
 { “coral”,               255, 127,  80 },
 { “coral light”,         240, 128, 128 },
 { “deep pink”,           255,  20, 147 },
 { “english red”,         212,  61,  26 },
 { “firebrick”,           178,  34,  34 },
 { “geranium lake”,       227,  18,  48 },
 { “hot pink”,            255, 105, 180 },
 { “indian red”,          176,  23,  31 },
 { “light salmon”,        255, 160, 122 },
 { “madder lake deep”,    227,  46,  48 },
 { “maroon”,              176,  48,  96 },
 { “pink”,                255, 192, 203 },
 { “pink light”,          255, 182, 193 },
 { “raspberry”,           135,  38,  87 },
 { “red”,                 255,   0,   0 },
 { “rose madder”,         227,  54,  56 },
 { “salmon”,              250, 128, 114 },
 { “tomato”,              255,  99,  71 },
 { “venetian red”,        212,  26,  31 }
};

struct colour browntab[] = {
 { “beige”,               163, 148, 128 },
 { “brown”,               128,  42,  42 },
 { “brown madder”,        219,  41,  41 },
 { “brown ochre”,         135,  66,  31 },
 { “burlywood”,           222, 184, 135 },
 { “burnt sienna”,        138,  54,  15 },
 { “burnt umber”,         138,  51,  36 },
 { “chocolate”,           210, 105,  30 },
 { “deep ochre”,          115,  61,  26 },
 { “flesh”,               255, 125,  64 },
 { “flesh ochre”,         255,  87,  33 },
 { “gold ochre”,          199, 120,  38 },
 { “greenish umber”,      255,  61,  13 },
 { “khaki”,               240, 230, 140 },
 { “khaki dark”,          189, 183, 107 },
 { “light beige”,         245, 245, 220 },
 { “peru”,                205, 133,  63 },
 { “rosy brown”,          188, 143, 143 },
 { “raw sienna”,          199,  97,  20 },
 { “raw umber”,           115,  74,  18 },
 { “sepia”,                94,  38,  18 },
 { “sienna”,              160,  82,  45 },
 { “saddle brown”,        139,  69,  19 },
 { “sandy brown”,         244, 164,  96 },
 { “tan”,                 210, 180, 140 },
 { “van dyke brown”,       94,  38,   5 }
};

struct colour orangetab[] = {
 { “cadmium orange”,    255,  97,   3 },
 { “cadmium red_light”, 255,   3,  13 },
 { “carrot”,            237, 145,  33 },
 { “dark orange”,       255, 140,   0 },
 { “mars orange”,       150,  69,  20 },
 { “mars yellow”,       227, 112,  26 },
 { “orange”,            255, 128,   0 },
 { “orange red”,        255,  69,   0 },
 { “yellow ochre”,      227, 130,  23 }
};

struct colour yellowtab[] = {
 { “aureoline yellow”,     255, 168,  36 },
 { “banana”,               227, 207,  87 },
 { “cadmium lemon”,        255, 227,   3 },
 { “cadmium yellow”,       255, 153,  18 },
 { “cadmium yellow light”, 255, 176,  15 },
 { “gold”,                 255, 215,   0 },
 { “goldenrod”,            218, 165,  32 },
 { “goldenrod dark”,       184, 134,  11 },
 { “goldenrod light”,      250, 250, 210 },
 { “goldenrod pale”,       238, 232, 170 },
 { “light goldenrod”,      238, 221, 130 },
 { “melon”,                227, 168, 105 },
 { “naples yellow deep”,   255, 168,  18 },
 { “yellow”,               255, 255,   0 },
 { “yellow light”,         255, 255, 224 }
};

struct colour greentab[] = {
 { “chartreuse”,          127, 255,   0 },
 { “chrome oxide green”,  102, 128,  20 },
 { “cinnabar green”,       97, 179,  41 },
 { “cobalt green”,         61, 145,  64 },
 { “emerald green”,         0, 201,  87 },
 { “forest green”,         34, 139,  34 },
 { “green”,                 0, 255,   0 },
 { “green dark”,            0, 100,   0 },
 { “green pale”,          152, 251, 152 },
 { “green yellow”,        173, 255,  47 },
 { “lawn green”,          124, 252,   0 },
 { “lime green”,           50, 205,  50 },
 { “mint”,                189, 252, 201 },
 { “olive”,                59,  94,  43 },
 { “olive drab”,          107, 142,  35 },
 { “olive green dark”,     85, 107,  47 },
 { “permanent green”,      10, 201,  43 },
 { “sap green”,            48, 128,  20 },
 { “sea green”,            46, 139,  87 },
 { “sea green dark”,      143, 188, 143 },
 { “sea green medium”,     60, 179, 113 },
 { “sea green light”,      32, 178, 170 },
 { “spring green”,          0, 255, 127 },
 { “spring green medium”,   0, 250, 154 },
 { “terre verte”,          56,  94,  15 },
 { “viridian light”,      110, 255, 112 },
 { “yellow green”,        154, 205,  50 },
};

struct colour cyantab[] = {
 { “aquamarine”,        127, 255, 212 },
 { “aquamarine medium”, 102, 205, 170 },
 { “cyan”,              000, 255, 255 },
 { “cyan white”,        224, 255, 255 },
 { “turquoise”,         064, 224, 208 },
 { “turquoise dark”,    000, 206, 209 },
 { “turquoise medium”,  072, 209, 204 },
 { “turquoise pale”,    175, 238, 238 }
};

struct colour bluetab[] = {
 { “alice blue”,        240, 248, 255 },
 { “blue”,                0,   0, 255 },
 { “blue light”,        173, 216, 230 },
 { “blue medium”,         0,   0, 205 },
 { “cadet”,              95, 158, 160 },
 { “cobalt”,             61,  89, 171 },
 { “cornflower”,        100, 149, 237 },
 { “cerulean”,            5, 184, 204 },
 { “dodger blue”,        30, 144, 255 },
 { “indigo”,              8,  46,  84 },
 { “manganese blue”,      3, 168, 158 },
 { “midnight blue”,      25,  25, 112 },
 { “navy”,                0,   0, 128 },
 { “peacock”,            51, 161, 201 },
 { “powder blue”,       176, 224, 230 },
 { “royal blue”,         65, 105, 225 },
 { “slate blue”,        106,  90, 205 },
 { “slate blue dark”,    72,  61, 139 },
 { “slate blue light”,  132, 112, 255 },
 { “slate blue medium”, 123, 104, 238 },
 { “sky blue”,          135, 206, 235 },
 { “sky blue deep”,       0, 191, 255 },
 { “sky blue light”,    135, 206, 250 },
 { “steel blue”,         70, 130, 180 },
 { “steel blue light”,  176, 196, 222 },
 { “turquoise blue”,      0, 199, 140 },
 { “ultramarine”,        18,  10, 143 }
};

struct colour magentatab[] = {
 { “blue violet”,          138,  43, 226 },
 { “cobalt violet deep”,   145,  33, 158 },
 { “magenta”,              255,   0, 255 },
 { “orchid”,               218, 112, 214 },
 { “orchid dark”,          153,  50, 204 },
 { “orchid medium”,        186,  85, 211 },
 { “permanent red violet”, 219,  38,  69 },
 { “plum”,                 221, 160, 221 },
 { “purple”,               160,  32, 240 },
 { “purple medium”,        147, 112, 219 },
 { “ultramarine violet”,    92,  36, 110 },
 { “violet”,               143,  94, 153 },
 { “violet dark”,          148,   0, 211 },
 { “violet red”,           208,  32, 144 },
 { “violet red medium”,    199,  21, 133 },
 { “violet red pale”,      219, 112, 147 }
};

struct colour namedtab[] = {
 { “aqua”,      0, 255, 255 },
 { “black”,     0,   0,   0 },
 { “blue”,      0,   0, 255 },
 { “fuchsia”, 255,   0, 255 },
 { “gray”,    128, 128, 128 },
 { “green”,     0, 128,   0 },
 { “lime”,      0, 255,   0 },
 { “maroon”,  128,   0,   0 },
 { “navy”,      0,   0, 128 },
 { “olive”,   128, 128,   0 },
 { “purple”,  128,   0, 128 },
 { “red”,     255,   0,   0 },
 { “silver”,  192, 192, 192 },
 { “teal”,      0, 128, 128 },
 { “white”,   255, 255, 255 },
 { “yellow”,  255, 255,   0 }
};

struct tabs {
 struct colour *table;
 int tabsize;
} coltab[TOTAL_COLORS];

int main(void) {
  enum colours { WHITE, GREY, BLACK, RED, BROWN, ORANGE, YELLOW,
                 GREEN, CYAN, BLUE, MAGENTA, NAMED } color;

 char *colourname[] = { “white”, “grey”, “black”, “red”, “brown”, “orange”,
                        “yellow”, “green”, “cyan”, “blue”, “magenta”,
                        “named colors” };
 int i = 0;
 int red = 0, green = 0, blue = 0;

 coltab[WHITE].table = whitetab;
 coltab[WHITE].tabsize = sizeof(whitetab) / sizeof(whitetab[0]);
 coltab[GREY].table = greytab;
 coltab[GREY].tabsize = sizeof(greytab) / sizeof(greytab[0]);
 coltab[BLACK].table = blacktab;
 coltab[BLACK].tabsize = sizeof(blacktab) / sizeof(blacktab[0]);
 coltab[RED].table = redtab;
 coltab[RED].tabsize = sizeof(redtab) / sizeof(redtab[0]);
 coltab[BROWN].table = browntab;
 coltab[BROWN].tabsize = sizeof(browntab) / sizeof(browntab[0]);
 coltab[ORANGE].table = orangetab;
 coltab[ORANGE].tabsize = sizeof(orangetab) / sizeof(orangetab[0]);
 coltab[YELLOW].table = yellowtab;
 coltab[YELLOW].tabsize = sizeof(yellowtab) / sizeof(yellowtab[0]);
 coltab[GREEN].table = greentab;
 coltab[GREEN].tabsize = sizeof(greentab) / sizeof(greentab[0]);
 coltab[CYAN].table = cyantab;
 coltab[CYAN].tabsize = sizeof(cyantab) / sizeof(cyantab[0]);
 coltab[BLUE].table = bluetab;
 coltab[BLUE].tabsize = sizeof(bluetab) / sizeof(bluetab[0]);
 coltab[MAGENTA].table = magentatab;
 coltab[MAGENTA].tabsize = sizeof(magentatab) / sizeof(magentatab[0]);
 coltab[NAMED].table = namedtab;
 coltab[NAMED].tabsize = sizeof(namedtab) / sizeof(namedtab[0]);

 for(color = WHITE; color < TOTAL_COLORS; color++) {
  printf(“\n ==> %s <==\n”, colourname[color]);
  for(i = 0; i < coltab[color].tabsize; i++) {
   red   = coltab[color].table[i].red;
   green = coltab[color].table[i].green;
   blue  = coltab[color].table[i].blue;
 
   printf(” %03d %03d %03d – #%02x%02x%02x – %s\n”,
     red, green, blue, red, green, blue, coltab[color].table[i].name);
  }
 }

 return 0;
}