facebook like button

25 August, 2011

A program to count the occurrences of a string in a given text

The need: 
     This is a simple program to count the occurrences of a string in a given text. The code is straight forward and uses built-in function strstr().
The code: 
---------------------------------------------------------

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

int count_occur(char *big, char *small);

int main()
{
    char big_string[]="The fat cat sat on a mat",search_string[]="at";
    printf("total %d occurrences found\n",count_occur(big_string,search_string));
    return 0;
}

int count_occur(char *big, char *small)
{
    char *temp;
    int count=0;
    temp=strstr(big,small);
    while (temp!=NULL)
    {
        temp=strstr(temp+1,small);
        count++;
    }
    return (count);
}
--------------------------------------------------------

18 August, 2011

program 78: do everything with linked list

The need:
This is a program to show almost all basic operations on linked lists. This program is just a combination of various programs of linked lists written by me. This is written in a way that you can pick data and function definitions and can use as-it-is in other programs.
The code:
------------------------------------------------------------
#include<stdio.h> 
#include<stdlib.h> 

// defining data-type node 
struct linked_list 
{ 
    int num;
    struct linked_list *next;
}; 
typedef struct linked_list node ;   //defining datatype node 

//declaration of functions 

node *create_list(node *p); 
node *reverse(node *p); 
int count (node *p); 
void print(node *p); 
node *insert(node *p); 
node *find(node *p,int a); 
node *hatana(node *p); 
node *insert_sort(node *head,int n); 
void sort(node *p); 
node *rearrange(node *p); 

main() 
{ 
    int i;
    node *head=NULL ;
    printf("This is a program to do with linked list .\n\n");
    lebel:
    printf("Options :\n(1)Create linked list.\n(2)view list.\n(3)Insert element.\n(4)Delete Element.\n");
    printf("(5)To arrange list in increasing order.\n");
    printf("(6)To remove double entries .\n(7)to reverse the list\n(8)Exit program.\n");
    scanf("%d",&i);
    switch(i)
    {
        case 1 :
                printf("Enter element numbers .\n");
                printf("Type -999 to end :\n");
                head=create_list(head);
                printf("List created successfully .\nNumber of items in the list are %d.\n\n\n",count(head));
                goto lebel;
        case 2 :
                print(head);
                goto lebel ;
        case 3 :         
                head=insert(head);
                goto lebel ;
        case 4 :         
                head=hatana(head);
                goto lebel ;
        case 5 :
                sort(head);
                printf("\nsorted in increasing order\n\n");
                goto lebel;
        case 6 :
                rearrange(head);
                printf("\nduplicate entries deleted\n\n");
                goto lebel;
        case 7 :
                head=reverse(head);
                printf("\nList reversed\n\n");
                goto lebel;
        case 8 :
                exit (0);
                break;         
        default:     
                printf("Invalid Choice !!!.\n");
                goto lebel ;
                break;
    }
     
     
    return 0;
        
}                //main ends here 

node *create_list(node *list) 
{ 
    int i;
    list=NULL;
    scanf("%d",&i);
    if(i!=-999)
    {
        list=(node*)malloc(sizeof(node));
        list->num=i;
        list->next=create_list(list->next);
    }
    return list;
} 

node *reverse(node *p) 
{ 
    node *temp=NULL,*rev=NULL;
    while(p)
    {
        temp=p;
        p=p->next;
        temp->next=rev;
        rev=temp;
    }
    return(rev);
} 

int count (node *list) 
{ 
    if(list==NULL)
    return 0;
    else
    return (1+count(list->next));            //recursion 
} 


void print(node *list) 
{ 
    if(list==NULL)
    printf("The list is empty.\n\n");
    else
    {
        printf("%d-->",list->num);
        if(list->next==NULL)
        printf("END\n\n\n");
        else
        print(list->next);            //recursion 
    }
} 



node *find(node *list, int key)            //This function returns the node after which 
{     
    if(list->next)
    {                                    //the key is found .                             
        if(list->next->num == key)     /* key found */ 
            return(list);
        else if(list->next->next == NULL)    /* end */ 
            return(NULL);
        else
        find(list->next, key);
    }
    else
    return NULL;
} 



node *insert(node *head) 
{ 
    node *new_node;          /* pointer to new node */ 
    node *n1=head;        /* pointer to node preceding key node */ 
    int key;
    int x;            /* new item (number) to be inserted */ 
    if(!head)
    {
        printf("\nlist is not created yet.\n\n");
        return head;
    }
    printf("What value you want to insert?");
    scanf("%d", &x);
    printf("before which key item ? (type -999 if to be inserted last) ");
    scanf("%d", &key);

    if(key==-999)        /* insert new node at last*/ 
    {
        while(n1->next)
            n1=n1->next;    //navigate to last node 
            
        new_node = (node *)malloc(sizeof(node));
        new_node->num = x;
        new_node->next = n1->next;
        n1->next = new_node;
    }
    else if(head->num == key)        /* new node is first */ 
    {
        new_node = (node *)malloc(sizeof(node));
        new_node->num = x;
        new_node->next = head;
        head = new_node;
    }
    else        /* find key node and insert new node */ 
    {            /* before the key node */ 
        n1 = find(head, key);    /* find key node */

        if(n1 == NULL&&key!=-999)
           printf("\n key is not found !!!\n\n");
            
        else        /* insert new node */ 
        {
          new_node = (node *)malloc(sizeof(node));
          new_node->num = x;
          new_node->next = n1->next;
          n1->next = new_node;
        }
      }
      return head;
} 



node *hatana(node *list) 
{ 
    void delete_node(node *);
    node *n1,*n2;
    int key;
    if(!list)
    {
        printf("\nlist is not created yet.\n\n");
        return list;
    }
    printf("What value do you want to delete ?");
    scanf("%d",&key);
    if(key==list->num)                        //key is the first node 
    {
        n2=list->next;
        free(list);
        list=n2;
        printf("\n%d is deleted successfully .\n\n",key);
    }
    else
    {
         n1=find (list ,key);
         if(n1)
        {
            delete_node(n1);                        //This function deletes n1->next 
            printf("\n%d is deleted successfully .\n\n",key);
        }
         else
         printf("\nItem is not in the list !!! \n\n\n");
    }
return(list); 
} 


void delete_node(node *list)  //This function deletes list->next 
{ 
    node *n2;
    n2=list->next->next;
    free(list->next);
    list->next=n2;
} 



node *rearrange(node *list) 
{ 
    node *p1;
    sort(list);
    for(p1=list;p1->next!=NULL;p1=p1->next)
    {
        if(p1->num==p1->next->num)
        delete_node(p1);
    }
    return(list);
} 


void sort(node *list) 
{ 
    void exchange(int *s1,int *s2);
    node *p,*q;
    for(p=list;(p->next)!=NULL;p=p->next)
        for(q=list;(q->next)!=NULL;q=q->next)
        {
            if(q->num > q->next->num)            //simple bubble sort 
            exchange(&(q->num),&(q->next->num));
        }
} 

void exchange(int *s1,int *s2) 
{ 
    int temp;
    temp =*s1;
    *s1=*s2;
    *s2=temp;
}
------------------------------------------------------------
Remarks:
This program has a small bug try and find out.

17 August, 2011

Program 77: Queue implementation on linked lists general case

The need:
    This program shows how one can implement concept of queue in linked lists. This is extension of previous program. This program is analogous to program75 of this blog.
The code:

------------------------------------------------------
/*
This is a program showing the queue implimentation on linked list
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node1
{
    int item;
    struct node1 *next;
};
typedef struct node1 node;        //defining datatype node

struct q1
{
    node *front;
    node *rear;
    int length;
};
typedef struct q1 queue;        //defining queue datatype

void enqueue(node *, queue *);
node *dequeue(queue *);
int queue_length(queue *);
void view_queue(queue *);
node *create_node(void);
void fill_node(node *);


int main()
{
    int i,j;
    node *current_node;
    queue que;                    //local queue
    que.front=NULL;
    que.rear=NULL;
    que.length=0;
    printf("This is a demo program to show working of queues");
    anchor:                    //anchor is a label
    printf("\n\nyou have following options\n");
    printf("1. enqueue an item\n2. dequeue an item\n3. view queue\n");
    printf("4. count items in queue\n5. exit program\n\n");
    scanf("%d",&j);
    switch(j)
    {
        case 1:
            printf("\nEnter a number to be enqueued =>\t");
            current_node=create_node();
            fill_node(current_node);
            enqueue(current_node, &que);
            goto anchor;
        case 2:
            current_node = dequeue(&que);
            if(current_node)
            printf("The item %d dequeued successfully\n",current_node->item);
            goto anchor;
        case 3:
            view_queue(&que);
            goto anchor;
        case 4:
            printf("total items in the queue are %d\n",que.length);
            goto anchor;
        case 5:
            printf("Thank you\n");
            exit(0);
            goto anchor;
        default:
            printf("Invalid choice...!!!\n try choosing again\n\n");
            goto anchor;
    }
  
    return 0;
}

void enqueue(node *p,queue *q)                    //definition of enqueue function
{
    if(q->rear==NULL&&q->front==NULL)
    {
        q->rear=p;
        q->front=p;
    }
    else
    {
        q->rear->next=p;
        q->rear=p;
    }
    q->length++;
    printf("item %d enqueued successfully.\n",p->item);
}

node *dequeue(queue *q)                    //definition of dequeue function
{
    node *temp=NULL;
    if(q->rear==NULL&&q->front==NULL)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
        return temp;
    }
    else if(q->rear==q->front&&q->front!=NULL)    //this is the case when queue has only one node
    {
        temp=q->front;
        q->front=NULL;
        q->rear=NULL;
    }
    else
    {
        temp=q->front;
        q->front=q->front->next;
    }
    q->length--;
    return temp;
}

void view_queue(queue *q)
{
    node *temp_front;
    temp_front=q->front;
    if(q->length==0)
    {
        printf("\nThe queue is empty...!!!\n");
        return;
    }
    printf("The queue is\n");
    while(temp_front!=NULL)
    {
        printf("%d -> ",temp_front->item);
        temp_front=temp_front->next;
    }
    printf("\n");
    return;
}

node *create_node()                    //function to create a blank node
{
    node *temp;
    temp=(node*)malloc(sizeof(node));
    temp->next=NULL;
    return temp;
}

void fill_node(node *p)                    //function to fill a blank node with values taken from user
{
    int i;
    scanf("%d",&i);                    //this is the value taken from user
    p->item=i;
}

------------------------------------------------------

program 76: Queue implementation on linked list

The need:
    This program shows how one can implement concept of queue in linked lists. I have already told that linked lists are needed when we practically don't want a bound on size of data being used in program. So unlike array implementation this program will never show "cannot enqueue" message until your computer is out of memory.
The code:

------------------------------------------------------


/*
This is a program showing the queue implimentation on linked list
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node1
{
    int item;
    struct node1 *next;
};
typedef struct node1 node;        //defining datatype node
void enqueue(node *);
node* dequeue(void);
node *create_node(void);
void fill_node(node *);
void print_node(node *);

node *front=NULL, *rear=NULL;                //global implementation of queue

int main()
{
    int i,j;
    node *current_node;
    printf("Enter 3 items into queue\n");
    for(i=0;i<3;i++)
    {
        current_node=create_node();
        fill_node(current_node);
        enqueue(current_node);
        printf("item %d inserted into queue successfully\n",current_node->item);
    }
    printf("all items successfully entered into queue\n");
    printf("press any key to dequeue and see all values you entered");
    fflush(stdin);
    getchar();
    while(!(rear==NULL&&front==NULL))
    {
        current_node=dequeue();
        print_node(current_node);
    }
    return 0;
}

void enqueue(node *p)                    //definition of enqueue function
{
    if(rear==NULL&&front==NULL)
    {
        rear=p;
        front=p;
    }
    else
    {
        rear->next=p;
        rear=p;
    }
}

node *dequeue(void)                    //definition of dequeue function
{
    node *temp=NULL;
    if(rear==NULL&&front==NULL)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
    }
    else if(rear==front&&front!=NULL)    //this is the case when queue has only one node
    {
        temp=front;
        front=NULL;
        rear=NULL;
    }
    else
    {
        temp=front;
        front=front->next;
    }
    return temp;
}

node *create_node()                    //function to create a blank node
{
    node *temp;
    temp=(node*)malloc(sizeof(node));
    temp->next=NULL;
    return temp;
}

void fill_node(node *p)                    //function to fill a blank node with values taken from user
{
    int i;
    printf("Enter an integer\n");
    scanf("%d",&i);                    //this is the value taken from user
    p->item=i;
}

void print_node(node *p)                    //printing the node data
{
    printf("%d\n",p->item);            //in our case node has only one item
}

------------------------------------------------------

Program 75: Circular Queues implementation on local Array

The need:
    To show how circular queue can be implemented on integer array with user defined functions (UDFs). This is general implementation of queues. This lets you handle more than one  queue by using same functions for all queues. For this some changes are made UDFs.
The code:
-----------------------------------------------------------
/*
This is a program showing the circular queue implimentation on array.
This program shows how we can implement queue on local variables.
In this first I have defined a structure containinf an array and front and rear
so that I can have front and rear for each local queue.
You can have multiple queues in this program all you need to do is 
declare another variable of type node.
In this convention front indexeses to the first item
and rear indexes the location after last item
this convention lets you fill maximum (SIZE-1) items in a queue
where SIZE is size of the array being used
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#define SIZE 5
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct node1
{
    int array[SIZE];
    int front,rear;
};
typedef struct node1 queue;

void enqueue(int, queue *);
int dequeue(queue *);
int queue_length(queue *);
void view_queue(queue *);

int main()
{
    int i=0,j,current_item;
    char c;
    queue que;            //local implementation of queue
    que.front=0;
    que.rear=0;
    printf("This is a demo program to show working of queues");
    anchor:                    //anchor is a label
    printf("\n\nyou have following options\n");
    printf("1. enqueue an item\n2. dequeue an item\n3. view queue\n");
    printf("4. count items in queue\n5. exit program\n\n");
    scanf("%d",&j);
    switch(j)
    {
        case 1:
            printf("\nEnter a number to be enqueued =>\t");
            scanf("%d",&current_item);
            enqueue(current_item, &que);
            goto anchor;
        case 2:
            current_item = dequeue(&que);
            goto anchor;
        case 3:
            view_queue(&que);
            goto anchor;
        case 4:
            printf("total items in the queue are %d\n",queue_length(&que));
            goto anchor;
        case 5:
            printf("Thank you\n");
            exit(0);
            goto anchor;
        default:
            printf("Invalid choice...!!!\n try choosing again\n\n");
            goto anchor;
    }
   
    return 0;
}

void enqueue(int a, queue *p)                    //definition of enqueue function
{
    if((p->rear+1)%SIZE==p->front)
        printf("cannot enqueue because the queue is already full.\n");
    else
        {
            p->array[p->rear]=a;                    //enqueing an item
            p->rear=(p->rear+1)%SIZE;
            printf("item %d inserted into queue successfully\n\n",a);
        }
}

int dequeue(queue *p)                    //definition of dequeue function
{
    int temp;
    if(p->rear==p->front)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
    }
    else
    {
        temp=p->array[p->front];
        p->front=(p->front+1)%SIZE;
        printf("item %d dequeued successfully\n",temp);
    }
    return temp;
}

int queue_length(queue *p)
{
    int length=0;
    if(p->rear>=p->front)
    length=p->rear-p->front;
    else
    length=(p->rear+SIZE)-p->front;
    return length;
}

void view_queue(queue *p)
{
    int temp_front;
    temp_front=p->front;
    if(queue_length(p)==0)
    {
        printf("\nThe queue is empty...!!!\n");
        return;
    }
    printf("The queue is\n");
    while(temp_front!=p->rear)
    {
        printf("%d -> ",p->array[temp_front]);
        temp_front=(temp_front+1)%SIZE;
    }
    printf("\n");
    return;
}

-----------------------------------------------------------
Remarks:
This is a program showing implementation of circular queue on array. For simplicity I have taken a simple integer array. This program may look different from previous ones but this is also simply follows the concept of queue.

Program 74: Circular Queue implementation on array using UDFs

The need:
    To show how circular queue can be implemented on integer array with user defined functions (UDFs). For sake of simplicity in UFFs I have taken array as global variable.
The code:
-----------------------------------------------------------
/*
This is a program showing the queue implementation on an array
In this front and rear are taken global variables
We can also have a program in which these are not global variables
In this convention front indexes to the first item
and rear indexes the location after last item
this convention lets you fill maximum (SIZE-1) items in a queue
where SIZE is size of the array being used
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#define SIZE 5
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void enqueue(int);
int dequeue(void);
int queue_length(void);
void view_queue(void);

int queue[SIZE];                //global implementation of queue
int  front=0, rear=0;        //my convention

int main()
{
    int i=0,j,current_item;
    char c;
    printf("This is a demo program to show working of queues");
    anchor:                    //anchor is a label
    printf("\n\nyou have following options\n");
    printf("1. enqueue an item\n2. dequeue an item\n3. view queue\n");
    printf("4. count items in queue\n5. exit program\n\n");
    scanf("%d",&j);
    switch(j)
    {
        case 1:
            printf("\nEnter a number to be enqueued =>\t");
            scanf("%d",&current_item);
            enqueue(current_item);
            goto anchor;
        case 2:
            current_item = dequeue();
            goto anchor;
        case 3:
            view_queue();
            goto anchor;
        case 4:
            printf("total items in the queue are %d\n",queue_length());
            goto anchor;
        case 5:
            printf("Thank you\n");
            exit(0);
            goto anchor;
        default:
            printf("Invalid choice...!!!\n try choosing again\n\n");
            goto anchor;
    }
   
    return 0;
}

void enqueue(int p)                    //definition of enqueue function
{
    if((rear+1)%SIZE==front)
        printf("cannot enqueue because the queue is already full.\n");
    else
        {
            queue[rear]=p;                    //enqueing an item
            rear=(rear+1)%SIZE;
            printf("item %d inserted into queue successfully\n\n",p);
        }
}

int dequeue(void)                    //definition of dequeue function
{
    int temp;
    if(rear==front)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
    }
    else
    {
        temp=queue[front];
        front=(front+1)%SIZE;
        printf("item %d dequeued successfully\n",temp);
    }
    return temp;
}

int queue_length(void)
{
    int length=0;
    if(rear>=front)
    length=rear-front;
    else
    length=(rear+SIZE)-front;
    return length;
}

void view_queue(void)
{
    int temp_front;
    temp_front=front;
    if(queue_length()==0)
    {
        printf("\nThe queue is empty...!!!\n");
        return;
    }
    printf("The queue is\n");
    while(temp_front!=rear)
    {
        printf("%d -> ",queue[temp_front]);
        temp_front=(temp_front+1)%SIZE;
    }
    printf("\n");
    return;
}

-----------------------------------------------------------
Remarks:
This is a simple program showing implementation of circular queue concept on array. For simplicity I have taken a simple integer array. I have used some UDFs here. I just wanted to show that queue is an abstract entity, we may or may not use UDFs. Its all our wish. The only thing to remember is the concept of queue.

Program 73: Queue implementation on array using UDFs

The need:
    To show how queue can be implemented on integer array with user defined functions (UDFs). For sake of simplicity in UFFs I have taken array as global variable.
The code:
-----------------------------------------------------------
/*
This is a program showing the queue implimentation on array
In this front and rear are taken global variables
We can also have a program in which these are not global variables
In this convention front indexeses to the first item
and rear indexes the location after last item
this convention lets you fill maximum (SIZE-1) items in a queue where SIZE is size of array being used
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/
#define SIZE 10
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void enqueue(int);
int dequeue(void);
int queue_length(void);

int queue[SIZE];                //global implementation of queue
int  front=0, rear=0;        //my convention

int main()
{
    int i=0,j,current_item;
    char c;
    printf("Enter some items into queue\n");
    do
    {
        printf("\nEnter integer %d\t=>\t",++i);
        scanf("%d",&current_item);                    //this is the value taken from user
        enqueue(current_item);
        printf("Enter press y to enqueue more items. else press any other key.\n");
        fflush(stdin);
        c=getchar();
    }
    while(c=='y'||c=='Y');
    printf("all items successfully entered into queue\n");
    printf("value of front = %d\t rear = %d\n",front,rear);
    printf("length of queue is %d\n",rear-front);
    printf("\n\npress any key to dequeue and see all values you entered\n");
    fflush(stdin);
    getchar();
    while(queue_length()!=0)
    {
        printf("%d -> ",dequeue());
    }
    printf("\n\npress any key to quit\n");
    while(!kbhit())
    ;
    return 0;
}

void enqueue(int p)                    //definition of enqueue function
{
    if(rear==SIZE-1)
        printf("cannot enqueue because the array end has been reached.\n");
    else
        {
            queue[rear++]=p;                    //enqueing an item
            printf("item %d inserted into queue successfully\n\n",p);
        }
}

int dequeue(void)                    //definition of dequeue function
{
    int temp;
    if(rear==front)        //this is the case when queue is empty
    {
        printf("queue is empty hence can not be dequeued\n");
    }
    else
    {
        temp=queue[front++];
    }
    return temp;
}

int queue_length(void)
{
    int length=0;
    length=rear-front;
    return length;
}

-----------------------------------------------------------
Remarks:
This is a simple program showing implementation of queue concept on array. For simplicity I have taken a simple integer array. I have used some UDFs here. I just wanted to show that queue is an abstract entity, we may or may not use UDFs. Its all our wish. The only thing to remember is the concept of queue.

10 August, 2011

Program 72: Queue implementation on array

The need:
    To show how queue concept can be implemented on an array in the simplest way possible.
The code:
-----------------------------------------------------------

/*
This is a program showing the queue implimentation on integer array
We can have array implementation on array of any datatype including derived datatypes
This program does not include any user defined function
In this front and rear are taken as array indices
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/

#define MAX 10
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i=0,arr[MAX];
    char c='y';
    int front=0,rear=-1,current_item;        //I follow the convention of takingthese values of front and rear when queue is empty
    printf("Enter 3 items into queue\n");
    while(c=='y'||c=='Y')
    {
        printf("\nEnter integer %d\t=>\t",++i);
        scanf("%d",&current_item);                    //this is the value taken from user
        if(rear==MAX-1)
        printf("cannot enqueue because the array end has been reached.\n");
        else
        arr[++rear]=current_item;                    //enqueing an item
        printf("item %d inserted into queue successfully\n\n",current_item);
        printf("Enter press y to enqueue more items. else press any other key.\n");
        fflush(stdin);
        c=getchar();
    }
    printf("all items successfully entered into queue\n");
    printf("value of front = %d\t rear = %d\n",front,rear);
    printf("length of queue is %d\n",rear-front+1);
    printf("\n\npress any key to dequeue and see all values you entered\n");
    fflush(stdin);
    getchar();
    printf("all items you entered are listed below\n");
    while(front<=rear)
    {
        printf("%d\n",arr[front++]);                    //dequeing an item
    }
    return 0;
}

-----------------------------------------------------------
Remarks:
This is a simple program showing implementation of queue concept on array. For simplicity I have taken a simple integer array. I also have not used any UDFs here. I just wanted to show that queue is an abstract entity, we dont even need enqueue and dequeue to implement that on simplest level. The only thing to remember is the concept of queue.

09 August, 2011

Concept of Queues in C

      The queue is another type of data structure. This is analogous to a line of persons at a ticket counter. Like stack here in C queue also is not a physical variable or object which you can point out in the program and say that this is my queue variable. This is an abstraction.
      Let me explain this in a simple way. You people may have seen queues ( a line of entities or persons) in X-Ray baggage inspection machine or at ticket booking counter. In both the physical systems there is a region with two ends. We call these ends front and rear. Lets go by the example of ticket booking counter queue. In one of its ends the persons enter and exits from the other one. So you can observe that the person which was enters first will begetting out first at the other end and the person who went last will be getting out last. This was the real life example of queue. In technical area also concept is exact same. We call this First In First Out (FIFO) the concept of queues. I have already told you people that queue is an abstraction. Its just the implementation of the real world queue concept onto our programs. In programming wherever we treat a bulk of elements in the same manner as persons at ticket booking counter (in FIFO fashion) we say that this is implementation of queue. We can implement queue in two ways:
1. queue implementation in arrays.
2. queue implementation in linked lists.


     To understand the queue concept in programming perspective you people need to know 4 terms: 
1. element : is a member of queue may be of a derived or built in datatype.
2. front: is the the variable which holds the index(in case of array) or address (in case of linked list) of front element. 
3. rear: is the the variable which holds the index(in case of array) or address (in case of linked list) of rear element. 
4. enqueue() : is the user defined function to add an element in queue. The element is added to the rear end of the queue.
5. dequeue() : is the user defined function to remove an element from queue. The element is removed from the front end of the queue.


      Because the concept is same so both user defined functions enqueue() and dequeue() are used in both the implementations. The definitions of enqueue() and dequeue() are different for both implementations but the working is same as described above. Those definitions will be given in the upcoming programs.
To elaborate these implementations more programs will be put in next posts.


Remarks:
1. While programming you should not worry about the whole queue like where it resides, how to keep track of all elements etc. The queue is abstract thing. only things you need to concentrate on and to keep track are the front and rear.
2. Both the operations enqueue() or dequeue() are concerned with front and rear respectively. The element put by enqueue() in the queue always becomes the rear and the dequeue() function always removes the front element.
3. When dequeue removes the front element, the front variable points to next element which is now on the front.This is also true in real life examples of persons on the ticket booking counter. when the front person is takes the ticket and goes out of the queue, the person just after the previous one now at comes at front.

07 August, 2011

Program 71: Conversion to any base

The need:
    The program was given to me in my online quiz. Actually this is not the same program I made at that time. This is a modified one and I made it after 6 months of the quiz. This can also handle conversion of relatively large numbers.
The code:
----------------------------------------------------
/*base conversion from 10 to any base up to Z*/

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<conio.h>
double divide(double a,double b);
main()
   {char h;
do
{
 double k,m;
 int i=0,j,l;
 float str[100];
 char temp[100];
 printf("This is a program to convert decimal integers to any base less than 62\n");
 printf("'A' means 10 and so on. 'a' means 36 and so on\n");
 printf("\nEnter a decimal integer => ");
 scanf("%lf",&k);
 printf("Enter the base in which to be converted =>");
 scanf("%lf",&m);
 if(m==0)
 {
 printf("Please enter a natural number less than 36. program exiting..\n");
 exit(0);
 }
 while(k>0)
    {
 str[i]=fmod(k,m);
 k=divide(k,m);
 i++;
    } 
 l=i;
 j=l;
 for(i=0;j>=0;i++,j--)
  {
  if(str[i]<10)
  temp[j]= (int)str[i]+'0';
  else if(str[i]<36)
  temp[j]= (int)str[i]+'A'-10;
  else if(str[i]<62)
  temp[j]= (int)str[i]+'a'-36;
  if(m>61)
  {
  printf("base should be less than 62.\n");
  exit(1);
  }
  }
  printf("The conversion to base %.0f is => ",m);
 for(j=1;j<=l;j++)
printf("%c",temp[j]);
printf("\n\nWant to try more ? y/n");
fflush(stdin);
h=getchar();
}while(h=='y'||h=='Y');
printf("hit any key to continue...\n");
getche();
}
double divide(double a,double b)
{
 double d=0,e;
 for(e=1000000000000;e>=1;e/=10)
    {
    while(a>=e*b)
    {
  a-=e*b;
  d+=e;
 }
 } 
 return (d);
}


----------------------------------------------------


Remark:
  1. This program has a bug which is : "It works accurate upto 15digit numbers but it loses accuracy if the input number becomes larger than that." Try to find out.