C Source Code  [Program 11 - 20] 

Contents 

Previous Page <<

Next Page >>

Useful Links to C/C++


11. /* Program to search for a given element in an array of n elements using
   Linear search as well as Binary search.Display the numberof comparisions
   made in each case.The elements are assumed to be one of integers,real or
   character,the program should output the first occurance of search element,
   if present and output a suitable message otherwise. */

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

main()
{
  int ch,n,i,key,a[100],k;
  int bin();
  int lin();

  do
  {
    clrscr();
    printf("\n\t***** MAIN MENU *****\n");
    printf("\n1. Linear Search\n");
    printf("\n2. Binary Search\n");
    printf("\n3. Exit Program");
    printf("\n----------------------------------");
    printf("\nSelect any one of the above==>");
    scanf("%d",&ch);

    switch(ch)
    {
       case 1: printf("\nEnter the size of the array==>");
        scanf("%d",&n);
        printf("\nEnter the array elements\n");
        for(i=0;i<n;i++)
  scanf("%d",&a[i]);
        printf("\nEnter the search element==>");
        scanf("%d",&key);
        k=lin(a,key,n);
        if(k==-1)
  printf("\nELEMENT NOT FOUND\n");
        else
  printf("\nELEMENT FOUND AT POSITION %d",k);
        break;

       case 2: printf("\nEnter the size of the array==>");
        scanf("%d",&n);
        printf("\nEnter the array elements in ascending order\n");
        for(i=0;i<n;i++)
  scanf("%d",&a[i]);
        printf("\nEnter the search element==>");
        scanf("%d",&key);
        k=bin(a,key,n);
        if(k==-1)
  printf("\nELEMENT NOT FOUND\n");
        else
  printf("\nELEMENT FOUND AT POSITON %d\n",k);
        break;
       }            /* end switch               */
       if(ch!=3) getch();
  }
  while(ch!=3);                         /* end do while             */
}                                       /* end main                 */

int lin(int a[],int key,int n)          /* linear search function   */
{
  int i;
  for(i=0;(key!=a[i]&&i<n);i++)
    if(i<n)
    {
     printf("\nThe no of comparisions made is %d",i-1);
     return(i+1);
    }
    else
    {
     printf("\nThe number of comparisions made is %d",i);
     return(-1);
    }
}

int bin(int a[],int key,int n)          /* binary search function   */
{
  int mid;
  int low=0;
  int high=n-1;
  int j=0;

  while(low<=high)
  {
    mid=(low+high)/2;
    if(key==a[mid])
    {
       ++j;
       printf("The no of comparisions made is %d",j);
       return(mid+1);
    }
    else if(key<a[mid])
    {
       j++;
       high=mid-1;
    }
    else
    {
       j++;
       low=mid+1;
    }
  }     /* end while loop */
  printf("The number of comparisions made is %d",j);
  return(-1);
}

12. /* Write a program to sort an array of n elements using bubble sort if
 a) Elements are integers
 b) Elements are strings                                          */

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

main()
{
  int ch,a[10],n,j,i;
  char x[10][50];
  void bubi(int[],int);
  void bubs(char[10][50],int);

  do
  {
    clrscr();
    printf("\n\t ****** BUBBLE SORT ******\n");
    printf("\n1. To sort Integers\n");
    printf("\n2. To sort Strings\n");
    printf("\n3. Exit Program\n");
    printf("\n-------------------------------\n");
    printf("\nSelect any one of the above==>");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1: printf("\nEnter the size of the array==>");
     scanf("%d",&n);
     printf("\nEnter the numbers to be sorted\n");
     for(i=0;i<n;i++)
       scanf("%d",&a[i]);
     printf("\nThe numbers in sorted order is \n");
     bubi(a,n);
     for(i=0;i<n;i++)
       printf("%d\n",a[i]);
     break;

    case 2: printf("\nEnter the number of strings==>");
     scanf("%d",&n);
     printf("\nEnter the strings one after another\n");
     for(i=0;i<n;i++)
        scanf("%s",&x[i]);
     bubs(x,n);
     printf("\nThe sorted strings are \n");
     for(i=0;i<n;i++)
        printf("%s\n",&x[i]);

    }if(ch!=3) getch();                                 /* end switch   */
  }                                                     /* end do while */
  while(ch!=3);
}       /* end main     */

void bubi(int a[],int n)
{
  int i,j,t,ex;

  for(i=0;i<n-1;i++)
  {
    ex=0;
    for(j=0;j<n-i-1;j++)
       if(a[j]>a[j+1])
       {
   t=a[j];
   a[j]=a[j+1];
   a[j+1]=t;
   ++ex;
       }
    printf("\nIn %d pass,number of exchanges made is %d\n",i,ex);
    }
}

void bubs(char x[10][50],int n)
{
  int i,j,ex=0;
  char temp[50];

  for(i=0;i<n-1;i++)
  {
    ex=0;
    for(j=0;j<n-i-1;j++)
       if(strcmp(x[j],x[j+1])>0)
       {
  strcpy(temp,x[j]);
  strcpy(x[j],x[j+1]);
  strcpy(x[j+1],temp);
  ex++;
       }
    printf("In %d pass,number of exchanges made is %d\n",i,ex);
  }
} 

 

13. /* Pyramid of numbers using for loop (Feb.1995) */

#include<stdio.h>

main()
{
 int i;

 clrscr();
 for(i=0;i<=5;i++)
 {
   switch(i)
   {
    case 1: printf("\n%10d",i);
            break;
    case 2: printf("\n%8d%4d",i,i);
            break;
    case 3: printf("\n%6d%4d%4d",i,i,i);
            break;
    case 4: printf("\n%4d%4d%4d%4d",i,i,i,i);
            break;
    case 5: printf("\n%2d%4d%4d%4d%4d",i,i,i,i,i);
   }   /* end switch */
 }     /* end for    */
 getch();
}      /* end main   */
 

14./* program to count the number of vowels in a given string (Feb.1995) */

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

#define EOF '.'

main()
{
 int c,i=0;

 clrscr();
 printf("\nEnter a line of text ending with a '.' ==>");
 while((c=getchar())!=EOF)
  {
   if((c=='a')||(c=='e')||(c=='i')||(c=='o')||(c=='u'))
       i+=1;
  }
  printf("\nThe number of vowels in the given string is %d",i);
  getch();
}

15./* Write a C program to implement stack of size n using an array.The elements
   in the stack are to be one of integer or real type.The operations to be
   supported are:-
   a)PUSH
   b)POP
   c)DISPLAY
   The program should take into account the exceptions of stack overflow
   and stack underflow.  */

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

#define max 5

int top=-1,stack[max];
void push();
void pop();
void display();

main()
{
  int ch,x;
  clrscr();
  textbackground(9);textcolor(4+128);
  cprintf("      STACK IMPLEMENTATION        ");
  do
  { textbackground(11);
    printf("\n\n1.Push a element using a stack\n");
    printf("\n2.Pop a element using stack\n");
    printf("\n3.Display all the elements\n");
    printf("\n4.Exit Program\n");
    printf("\nSelect any one of the above==>");
    scanf("%d",&ch);
    switch(ch)
    {
      case 1: printf("\nEnter the element to be pushed into the stack==>");
       scanf("%d",&x);
       push(x);
       break;
      case 2: pop();
       break;
      case 3: display();
       break;
      default:printf("\nGoodbye.... and have a nice day!\n");
       getch();

    }
  }while(ch!=4);
}

void push(int x)
{
  if(top==max-1)
  {
 display();
 printf("Stack overflow....\n");
  }
  else
  {
 stack[++top]=x;
 display();
  }
  if(top==max-1)
  {
 display();
 printf("The stack is full....\n");
  }
}

void pop()
{
  if(top==-1)
 printf("\nStack underflow....\n");
  else
  {
 printf("\nThe popped item is %d\n",stack[top--]);
 if(top==-1)
        printf("\nThe stack is empty....\n");
  }
}

void display()
{
  int i;
  if(top==-1)
 printf("\nEmpty stack....\n");
  for(i=top;i>=0;i--)
 printf("\n------\n|%4d|\n",stack[i]);
}

/*16. Write a C program to evaluate suffix expression using stack.Assume the
expression is given in one line as a string of digits and operator symbols.
The operands are single nonnegative digits and operators are +,-,*,/ with
usual meaning.Further,it may be assumed that the input given represents a
valid suffix expression.*/

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

int top=-1,stack[50];

main()
{
 char k,k1,in[100],c;
 int value,i=0;

 void push();
 int pop();

 clrscr();
 printf("\nEnter the valid suffix expression:");
 gets(in);                   /* the i/p suffix expr is read as a string */
 while((c=in[i])!='\0')      /* each character or symbol of the i/p suffix expr is taken */
 {
  if(isalpha(in[i]))         /* checks if the scanned symbol is in A to Z or a to z */
  {
    printf("Enter the value of %c=",in[i]);
    scanf("%d",&value);      /* reads the value of the operand in the given suffix expr */
    push(stack,value);       /* puts the value of the operand on stack top */
  }
  else               /* else the i/p symbol must be any of the below mentioned operators */
  switch(c)
  {
   case '+': k=pop(stack)+pop(stack); /* performs addition operation with the first 2 elements in the stack */
      push(stack,k);   /* puts the result of the operation on the stack */
      break;
   case '-': k=-pop(stack)+pop(stack);
      push(stack,k);
      break;
   case '*': k=pop(stack)*pop(stack);
      push(stack,k);
      break;
   case '/': k=pop(stack);
      k1=pop(stack)/k;
      push(stack,k1);
      break;
   }
   i++;
  } /* end while */
  printf("\nThe value of given suffix expression is %d",stack[top]);
  getch();
}

void push(int stack[],int value)
{
 stack[++top]=value;
}

int pop(int stack[])
{
 return(stack[top--]);
}
 

/*17. Write a C program to convert an expression from infix form to suffix form
   using stack.The input is one line containing a string of characters.All the
   operands +,-,*,/ with usual meaning and order of precedence relations.The
   string may include left and right parenthesis which have the highest priority
   compared to other operators.The output should be a character string
   representing the input expression in suffix form.(Assume the input string
   represents a valid infix form.) */

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

#define MAX 20

int i=0,j=0,top=-1;
char infix[MAX],suffix[MAX],stack[MAX],push(),pop();

main()
{
 clrscr();
 printf("\nEnter a valid infix expression:");
 scanf("%s",infix);

 while(infix[i]!='\0')
 {
  switch(infix[i])
  {
   case '(': push(infix[i]);    /* push ( on to stack */
      break;
   case '+': push(infix[i]); /* push the operators on to stack */
      break;
   case '-': push(infix[i]);
      break;
   case '*': push(infix[i]);
      break;
   case '/': push(infix[i]);
      break;
   case ')': while(stack[top]!='(') /* pop all elements from stack until a ( is encountered */
      suffix[j++]=pop();
      pop();      /* pop the ( from stack */
      break;
   default:  suffix[j]=infix[i]; /* if infix[i]=operand,put it directly in suffix[]  */
      j++;
   }  /* end switch */
   i++;
  }  /* end while  */

  while(top!=-1)  /* when stack is not empty */
  {
   if(stack[top]=='(')  /* if stack top is ( then remove it */
 pop();
   suffix[j++]=pop();   /* pop the remaining stack elements on to suffix */
  }
  printf("\nConverted suffix expression:");
  for(i=0;suffix[i]!='\0';i++)
 printf("%c",suffix[i]);
  getch();
}

char push(char x) /* x= pushed element */
{                       /* a= stack top      */
 char a=stack[top];
 while((a!='(') && ((x=='+'|| x=='-')&&(a=='*'||a=='/')) || (x=='-' && a=='+'))
 {
  suffix[j++]=pop(); /*{1:The element or operator x is pushed on to        */
  a=stack[top];      /*   stack only if the stack top has a lower          */
 }       /*   precedence than the operator to be pushed.                    */
 stack[++top]=x;     /* 2:If the stack top operator has higher precedence  */
}       /*   than the operator to be pushed then the stack    */
       /*   top is poped to suffix[].                              */
       /* 3:Now the next operator in the stack becomes the   */
       /*   stack top and step 1. is repeated. }     */
char pop()
{
 return(stack[top--]);
}
 

/*18. Write a C program to implement a queue of integers using an array
      considered as circular queue.Operations to be supported are:
      a)Insertion b)Deletion c)Display
      Further implement a function which returns TRUE or FALSE depending on
      whether or not the queue is empty.During insertion and deletion,the
      program must check for queue full or queue empty conditions and issue
      appropriate messages.  */

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

int cirque[10],front,rear,n;
int del();
void insert(int);
void display(int);
int empty(int,int);
char full=0;

main()
{
 char c;
 int ch,x;

 clrscr();
 printf("\nInput the size of the queue==>");
 scanf("%d",&n);
 front=rear=0;
 do
 {
  printf("Press 1 for inserting\n");
  printf("Press 2 for deleting\n");
  printf("Press 3 for displaying the queue\n");
  printf("Press 4 to exit\n");
  printf("Enter your choice==>");
  scanf("%d",&ch);

  switch(ch)
  {
  case 1: printf("\nEnter the element to be inserted==>");
   scanf("%d",&x);
   insert(x);
   break;

  case 2: printf("\nThe element deleted is %d",del());
   break;

  case 3: display(front);
   break;
  }
 }while(ch!=4);
}

void insert(int x)
{
 if(!full)  /* if queue is not full */
 {
  cirque[rear++]=x;     /* insert at the rear end */
  if(rear==n)
 rear=0;
  if(rear==front)
  {
   printf("Queue full!\n");
   full=1;
  }
  return;
 }
 else
 {
  printf("Queue Overflow!\n");
  return;
 }
}

void display(int front)
{
 if(front!=rear||full)
 {
  int i;
  for(i=1;i<=n;i++)
  {
   printf("%d\n",cirque[front++]);
   if(front==n)
 front=0;
   if(front==rear)
 break;
  }
 }
}

int del()
{
 int y;
 if(empty(front,rear))
 {
  printf("Queue undeflow\n");     /* if the queue is already empty */
  return(0);
 }
 y=cirque[front++]; /* delete at the front end */
 if(front==n)
 front=0;
 if(front==rear)
 {
  printf("Queue is empty!\n");
  front=rear=0;
  full=0;
 }
 return(y);  /* to display the deleted element */
}

int empty(int front,int rear)
{
 if(front==rear && !full)
 return(1);
 else
 return(0);
}

/19. * Program to process a linear linked list of strings */
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>

#define NIULL 0

/* menu driven program to process a linked list of strings */

struct list_element {
 char item[40];   /* data item for this node */
 struct list_element *next;      /* pointer to the next node */
 };
typedef struct list_element node;       /* structure type declaration */

main()
{
 node *start; /*                      /* pointer to begining of list */
 int choice;

 int menu(void);
 void create(node *pt);
 node *insert(node *pt);
 node *del(node *pt);
 void display(node *pt);

 clrscr();
 do
 {
  choice=menu();

  switch(choice)
  {
   case 1: /* create the linked list */
    start=(node*)malloc(sizeof(node));  /* allocate space for first node */

    create(start);
    printf("\n");
    display(start);
    continue;

   case 2: /* add one component */
    start=insert(start);
    printf("\n");
    display(start);
    continue;

   case 3: /* delete one component */
    start=del(start);
    printf("\n");
    display(start);
    continue;

   case 4: /* display the linked list */
    if(start->next!=NULL)
  display(start);
    else
  printf("\nThe Linked List is empty!\n");

   default: /* terminate computation */
     printf("\nEnd of Computation");
   }        /* end switch  */
  }         /* end do while */
  while(choice!=5);
}     /* end main */

int menu(void)  /* generate the menu */
{
  int choice;
  do
  {
    printf("\n\tMAIN MENU\n");
    printf("-----------------------------------");
    printf("\n1 - CREATE the linked list");
    printf("\n2 - ADD a component");
    printf("\n3 - DELETE a component");
    printf("\n4 - DISPLAY linked list");
    printf("\n5 - EXIT program\n");
    printf("-----------------------------------");
    printf("\nSelect any one of the above==>");
    scanf("%d",&choice);
    if(choice<1||choice>5)
      printf("\nINVALID entry - please try again\n");
  }
  while(choice<1||choice>5);
  return(choice);
}  /* end menu */

void create(node *record)       /* create a linked list */
/* argument points to the current node */
{
 printf("\nData item (type 'END' when finished) :");
 scanf("%s",record->item);
 if(strcmpi(record->item,"END")==0)
 record->next=NULL;
 else
 {
  /* allocate space for next node */
  record->next=(node*)malloc(sizeof(node));
  /* create the next node */
  create(record->next);
  /* note that recursion has been used here */
 }
 return;
} /* end of create */

void display(node *record) /* display the linked list */
/* argument points to the current node */
{
 if(record->next!=NULL)
 {
  printf("\n%s",record->item); /* display this data item */
  display(record->next); /* get the next data item(recursion used) */
 }
 return;
}    /* end of display */

node *insert(node *first) /* add one component to the linked list */
/* returns pointer to the begining of the modified list */
{
 node *locate(node *,char[]); /* function declaration */
 node *newrecord;  /* pointer to new node */
 node *tag;   /* pointer to node before target node */
 char newitem[40];  /* new dataitem */
 char target[40];  /* data item following the new entry */

 printf("\nNew data item: ");
 scanf("%s",newitem);
 printf("\nPlace before (type 'END' if last) : ");
 scanf("%s",target);

 if(strcmpi(first->item,target)==0)
 { /* new node is first in line */
 /* allocate space for the new node */
  newrecord=(node*)malloc(sizeof(node));
 /* assign the new data item to newrecord->item */
  strcpy(newrecord->item,newitem);
 /* assign the current pointer to newrecord->next */
  newrecord->next=first;
 /* new pointer becomes the begining of the list */
  first=newrecord;
 }
 else
 { /* insert new node after an existing node */
 /* locate the node preceding the target node */
  tag=locate(first,target);
  if(tag==NULL)
    printf("\nMatch not found - Please try again\n");
  else
    {   /* allocate space for the new node */
      newrecord=(node*)malloc(sizeof(node));
 /* assign the new data item to newrecord->item */
      strcpy(newrecord->item,newitem);
 /* assign the next pointer to newrecord->next */
      newrecord->next=tag->next;
 /* assign the new pointer to tag->next */
      tag->next=newrecord;
    }
  }
  return(first);
}

node *locate(node *record,char target[]) /* locate a node */
/* return a pointer to the node before the target node
   first argument points to the current node
   second argument is the target string  */

{
 if(strcmpi(record->item,target)==0) /* found a match */
    return(record);
 else
    if(record->next->next==NULL)
       return(NULL);                /* end of list */
    else
       locate(record->next,target);     /* try next node (recursion) */
}

node *del(node *first)
/* delete one component from the linked list return pointer to begining of
   of modified list.
   argument points to the first node.  */

{
  node *locate(node *,char[]);  /* function declatration */
  node *tag; /* pointer to node before target node */
  node *temp;
  char target[40]; /* data item to be deleted */

  printf("Data item to be deleted: ");
  scanf("%s",target);
  if(strcmpi(first->item,target)==0)
  { /* delete the first node */
 /* mark the node following the target node */
    temp=first->next;
 /* free space for the target node */
    free(first);
 /* adjust the pointer to the first node */
    first=temp;
  }
  else /* delete a data item other then the first */
 /* locate the node preceding the target node */
    tag=locate(first,target);
    if(tag==NULL)
       printf("\nMatch not found - Please try again\n");
    else
       {     /* mark the node following the target node */
  temp=tag->next->next;
      /* free space for the target node */
  free(tag->next);
      /* adjust the link to the next node */
  tag->next=temp;
    }
    return(first);
}

/*20. Write a C program to create a subdirectory if it does not exist,
  using DOS interrupts.A suitable message should be displayed on CRT
  depending on the success or failure of operation   */

#include<stdio.h>
#include<dos.h>

union REGS inregs,outregs;
char newdir[10];

void main()
{
 printf("\nEnter New Directory Name:");
 scanf("%s",&newdir);
 inregs.x.dx=(int) &newdir; /* DOS function 39H is used to create subdir    */
 inregs.h.ah=0x39;  /* inregs.h.ah specifies the DOS function to be envoked */
 intdos(&inregs,&outregs);  /* intdos() executes DOS interrupt INT 21H      */
 if(outregs.x.cflag!=0)     /* carry flag is set if an error occurs         */
 printf("\nError! New Directory %s could not be created",newdir);
 else
 printf("\nNew Directory %s was created in current directory",newdir);
}
/* Note: After the INT 21H returns it copies the current registers and flags
   value to there corresponding fields in outregs */


Useful Links to C/C++

Contents 

Previous Page <<

Next Page >>

 © Copyrights Madhu Sudan Rao G.K

[CodeEverywhere.Com]