Wednesday, August 8, 2012

Animation in Java

Here is a Simple Animation Program in Java.

import java.awt.*;
import java.awt.event.*;

public class Animation extends Frame implements ActionListener,Runnable
{
    Button bStart,bExit;
    int i,j;
    Thread t;
    public Animation()
    {
        bStart = new Button("Start");
        bExit = new Button("Exit");
       
        setLayout(new FlowLayout());
        add(bStart);
        add(bExit);
       
        bStart.addActionListener(this);
        bExit.addActionListener(this);
    }
   
    public void run()
    {
        try
        {
            j = 0;
            for(i = 0 ; i < 100 ; i = i + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
            i=50;
            for(j = 0 ; j < 100 ; j = j + 2)
            {
                paint(getGraphics());
                t.sleep(100);
            }
        }
        catch(Exception e){}
    }
   
    public void start1()
    {
        t = new Thread(this);
        try
        {       
            t.start();
        }
        catch(Exception e)
        {
            System.out.println("Exception Occured : " + e);
        }
    }
   
    public void paint(Graphics g)
    {
        //Color c = new Color(i);
        //setForeground(c);
        //g.setColor(Color.BLUE);
        g.clearRect(0,0,this.getHeight(),this.getWidth());
        g.drawOval(50+j,50+i,30,30);       
        return;
    }

    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource() == bExit)
        {
            System.exit(1);
        }
        if(ae.getSource() == bStart)
        {
            System.out.println("Start Button Clicked...");
            start1();
        }
   
    }
    public static void main (String[] args)
    {   
        Animation a1 = new Animation();
        a1.setSize(400,400);
        a1.show();
    }
}

Menu Driven Program in Java

 A menu driven system which will perform following options for student data
 1) (Roll No,Name,Per)
 2) Insert, Update, Delete, Search  record
 3) Raise Exception if wrong data are entered like negative for roll no.

import java.io.*;
 import java.util.*;

 class NegativeNumberException extends Exception  { }


 class Slip5_9_13_2
 {
     public static void main(String agrs[]) throws IOException
     {
    
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       Student stud;
  &stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
         System.out.println("|------------------------------|");
         System.out.println("|\t [1] :Add \t\t|");
         System.out.println("|\t [2] :Insert \t\t|");
         System.out.println("|\t [3] :Update \t\t|");
         System.out.println("|\t [4] :Search \t\t|");
         System.out.println("|\t [5] :Delete \t\t|");
         System.out.println("|\t [6] :Print \t\t|");
         System.out.println("|\t [7] :Exit \t\t|");
          System.out.println("|------------------------------|");
         System.out.print("\nEnter Choice : ");
        
        
         try
          {
              ch=Integer.parseInt(br.readLine());
             
               switch(ch)
              {
                case 1:System.out.println("\nEnter Stud Details\n");
                       stud=new Student();
                       perfect=stud.read_data();   
                       if(perfect==1)
                           L.add(stud);
                       break;
                case 2:System.out.print("\nEnter Position where to insert record : ");
                        pos=Integer.parseInt(br.readLine());
                       if(pos>L.size())
                         {
                              System.out.println("\n\nPosition out of range\n\n");
                              break;
                         }   
                      
                       stud= new Student();
                       perfect=stud.read_data();
                       if(perfect==1)
                            L.add(pos,stud);
                       break;
                 case 3:System.out.print("\n Enter Roll no to update record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                         while(it.hasNext())
                         {
                           stud=(Student)it.next();
                           if(stud.rno==no)
                              {
                                 found=1;   
                                  pos=L.indexOf(stud);
                                L.remove(pos);// remove old record from specified pos
                               
                                perfect=stud.read_data();
                               
                                if(perfect==1)
                                     L.add(pos,stud);
                            
                                break;
                               }
                         } 
                       if(found!=0)  //found==0
                           System.out.println("\nRoll_No not present so Record Not Updated ");
                                               
                       break;        
                              
                case 4:System.out.print("Enter Rollno to search record : ");
                       no=Integer.parseInt(br.readLine());
                       found=0;
                       it=L.iterator();
                      
                       while(it.hasNext())
                       {
                           stud=(Student)it.next();
                            if(stud.rno==no)
                              {
                                  found=1;
                                  pos=L.indexOf(stud);
                                  System.out.println("\n\nReord Found at "+pos+" Position\n");
                                  stud.show_data();
                                 
                                  break;
                                 
                              }
                       }
                       if(found!=1)
                             System.out.println("\nRoll_No not present so Record Not Found");
                         
                      break;
                     
                case 5:System.out.print("\n Enter Roll no to delete record : ");
                        no=Integer.parseInt(br.readLine());
                        found=0;
                        it=L.iterator();
                       
                        while(it.hasNext())
                         {
                          stud=(Student)it.next();
                              if(stud.rno==no)
                            {
                                 found=1;
                                 L.remove(stud);
                                 System.out.print("\nRecord deleted succesfully \n");
                                 break;   
                               }
                         }
                        if(found!=1)
                          System.out.println("\nRoll_No not present so Record Not Deleted\n");
                        
                       break;
            
                case 6:System.out.println("\n\n|------* Student Details *-----|");
                       System.out.println("|------------------------------|");
                      System.out.println("|ROLL NO\t NAME\t PERCENTAGE|");
                      System.out.println("|------------------------------|");

                      it=L.iterator();

                      while(it.hasNext())
                       {
                             stud=(Student)it.next();
                             stud.show_data();
                       }
                      System.out.println("|------------------------------|");
                      break;
                case 7:System.exit(0);           
               
            
              }//switch
           }
         catch(NumberFormatException n)
         {   System.out.println("Exception "+n); }
        
       }while(ch!=7);
     }//main
    
 }// class slip


 class Student
 {
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     int rno;    // Roll no
     String name; //name
     double per;//percentage
    
     int  read_data() throws IOException
     {
         try
         {
        
             System.out.print("Roll No : ");
             rno=Integer.parseInt(br.readLine());
                if(rno<0)
                   throw new NegativeNumberException();
           
             System.out.print("Name : ");
             name=br.readLine();
            
             System.out.print("Percentage : ");
             per=Double.parseDouble(br.readLine());
                 if(per<0)
                     throw new NegativeNumberException();
            
          }
         
         catch(NegativeNumberException n)
         {
          System.out.println("Exception: Number Must be Positive");
           return 0;
         } 
       return 1;    
       
      }// read_data()
     
      void show_data()
      {
          System.out.println("| "+rno+"\t | "+name+" | "+per+" |");
      }  

 }

File Watcher Program in Java

Java Program to create a class called File Watcher that can be given several file names
that may or may not exist. the class should start a thread for each file name
Each thread will periodically check for the existence of it's file.
If the file exist,the thread will write a message to the console & then end.

import java.io.*;
class SlipFileWatch
{
 public static void main(String args[]) throws IOException
  {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n Enter Several N  files");
        try
        {
          int n =Integer.parseInt(br.readLine());
          System.out.println("\n Enter File name");
          for(int i=1;i<=n;i++)
                  new FileWatcher(br.readLine());
        }  
        catch(Exception e)
        { System.out.println("Invalid Input");}
    }
}   
   
class FileWatcher implements Runnable
{
    Thread T;
    String fname;
    FileWatcher(String fn)
    {
        fname=fn;
        T=new Thread(this,fname);
        System.out.println("\n\nNew = "+T);
        T.start();
    }
   
    public void run()
    {
        File f = new File(fname);
        if(f.exists())
          System.out.println(" "+fname+"  File Exist ");
        else 
          System.out.println(" "+fname+"  File Not Exist");
         try
          {
              Thread.sleep(1000);
          }
          catch(InterruptedException it){}
    }
}

Multiple Select Box and Combo box in Java

The java program given below does the following tasks,

 1) Button(<<) moves all items from list1 to list2.
 2) Button(<) moves single item from list1 to list2.
 3) Button(>>) moves all items from list2 to list1.
 4)Button(>) moves single item from list2 to list1.
  5)When 1 item is moved the next item should be highlighted automatically.
  6)No list box should contain duplicate entries
  7)Add & Remove button should work for their own list box & not for other

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;

public class Slip2_1 extends JFrame implements ActionListener
{
    List list1,list2;
    JButton b1,b2,b3,b4,b5,b6,b7,b8;
   
    JTextField t1;
  
    int i,j;
   // String d;
  
   

    public static void main(String args[])
       {
               Slip2_1  s = new Slip2_1();
              
       }
   
   // Container c=getContentPane();
       
    public Slip2_1()
    {
       
        super("List add/remove item ");
       
        setSize(550,450);
        setLocation(100,100);
        //setBounds(100,100,550,450);
        setVisible(true);
        setLayout(null);
       
        list1 = new List();
        list1.add("Ball");
        list1.add("Bat");
        list1.add("Stump");
        list1.add("Pad");
        list1.add("Gloves");
        list1.add("Shoes");
        list1.add("Helemet");
        list1.add("Bells");
        list1.add("Caps");
        list1.add("Medicine");
        list1.setBounds(75,100,90,200);
        add(list1);
       
        list2 = new List();
        list2.add("Computer");
        list2.add("Laptop");
        list2.add("Camera");
        list2.add("Veg");
        list2.add("Non_Veg");
        list2.add("Medicine");
        list2.setBounds(350,100,100,200);
        add(list2);
       
        b1 =new JButton("<<");
        b1.setBounds(225,100,75,25);
        add(b1);
       
        b2 =new JButton("<");
        b2.setBounds(225,150,75,25);
        add(b2);
       
        b3 =new JButton(">>");
        b3.setBounds(225,200,75,25);
        add(b3);
       
        b4 =new JButton(">");
        b4.setBounds(225,250,75,25);
        add(b4);
       
        //list1
        b5 =new JButton("Add");
        b5.setBounds(25,350,75,25);
        add(b5);
       
        b6 =new JButton("Remove");
        b6.setBounds(150,350,85,25);
        add(b6);
       
       
        //list2
        b7 =new JButton("Add");
        b7.setBounds(325,350,75,25);
        add(b7);
       
        b8 =new JButton("Remove");
        b8.setBounds(425,350,85,25);
        add(b8);
        
        
        b1.addActionListener(this) ;
        b2.addActionListener(this);
        b3.addActionListener(this) ;
        b4.addActionListener(this) ;
        b5.addActionListener(this);
        b6.addActionListener(this) ;
        b7.addActionListener(this) ;
        b8.addActionListener(this) ;
        
       
    }//slip2_1 constructor

 public void actionPerformed(ActionEvent ae)   
 {
    
    
     if(ae.getSource()==b1) // list1 << list2
     {
      // << copy all item from list1 to list2
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt1;i++)
      {
       int flag=0;
        for(int j=0;j<cnt2;j++)
          if(list1.getItem(i).equalsIgnoreCase(list2.getItem(j))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list2.add(list1.getItem(i));
       }
      list1.removeAll();    
       } // b1 list1 << list2
    
    
     if(ae.getSource()==b3) // list2 >> list1
     {
      //  copy all item from list2 to list1
       
     int cnt1 = list1.getItemCount();
     int cnt2 = list2.getItemCount();
     for(int i=0;i<cnt2;i++)
      {
       int flag=0;
        for(int j=0;j<cnt1;j++)
          if(list1.getItem(j).equalsIgnoreCase(list2.getItem(i))==true)
             {
                      flag=1;
                      break;
            }

          if(flag==0)
           list1.add(list2.getItem(i));
       }
      list2.removeAll();    
       }// b3  list1 >> list2
    
  String d;

   if(ae.getSource()==b2) // list1 < list2
   {
       // add single selected item from list1 to list2
       d =list1.getSelectedItem();
       int cnt = list2.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list2.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list2.add(d);
      
   }// b2 list1 < list2


 if(ae.getSource()==b4) // list1 > list2
   {
       // add single selected item from list2 to list1
       d =list2.getSelectedItem();
       int cnt = list1.getItemCount();
       for(i=0;i<cnt;i++)
        {
           if(list1.getItem(i).equals(d)) // d is selcted item from list1
            return;
        }
       list1.add(d);
      
   }// b4 list1 > list2
  
  
   if(ae.getSource()==b5)
            {
                 String m = "Enter the item";
                 String result  =JOptionPane.showInputDialog(m);
                 int cnti=0,cnt = list1.getItemCount();
                
                 if(result!=null)
                 if(result.equals("")!=true)
                   {
                     for(int i=0;i<cnt;i++)
                      {
                        if(result.equalsIgnoreCase(list1.getItem(i))==true)
                         {cnti=1; break;}
                      }
                    if(cnt==0 || cnti==0)
                    list1.add(result);
                  }
            }

         if(ae.getSource()==b6)
            {
                String m = "Enter the item";
                String result  = JOptionPane.showInputDialog(m);
                   list1.remove(result);
               }

           if(ae.getSource()==b7)
               {
            String res=JOptionPane.showInputDialog("Enter The Item");
                int cnti=0,cnt = list2.getItemCount();
           
                           
                if(res!=null)
                if(res.equals("")!=true)
                 {
                   for(int i=0;i<cnt;i++)
                    {
                      if(res.equalsIgnoreCase(list2.getItem(i))==true)
                       {cnti=1; break;}
                    }
                   if(cnt==0 || cnti==0)
                   list2.add(res);
                 }
              }

         if(ae.getSource()==b8)
             {
              String res= JOptionPane.showInputDialog("Enter the item");
                list2.remove(res);
             }

  
  

    
 }//actionperformed
   
}

HashTable In Java

Here is a Hash Table program in java.

In this program we are going to,

 1]Accept n  records of student(Name,percentage)
 2]Disply details of all students
 3]Find out highest marks

 import java.util.*;
 import java.io.*;
 class Slip1_2
 {
   public static void main(String args[]) throws IOException
   {
     
       Slip1_2 htc = new Slip1_2();
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int opt=1;
      while(opt!=4)
       {
         
           System.out.println("1:Enter Record");
           System.out.println("2:Disply Details");
           System.out.println("3:Find Highest Marks");
           System.out.println("4:Exit");
           System.out.print("Select Option : ");
      
        int r=Integer.parseInt(br.readLine());
      
        System.out.println();
        
           switch(r)
           {
               case 1:htc.get_record();      break;
               case 2:htc.disp_record();    break;
               case 3:htc.highest_record(); break;
               case 4:System.exit(0);
           }//switch
       }//while
     }//main


     Hashtable ht =new Hashtable();
     //Enumeration names;
     String nm;
    Slip1_2(){ }
    void get_record() throws IOException
     {
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       System.out.print("Enter n Records of stud : ");       int n=Integer.parseInt(br.readLine());
       Double d;
          System.out.println();
          for(int i=0;i<n;i++)
          {
               System.out.print("Enter Name : ");    nm = br.readLine();
              System.out.print("Enter Percentage : ");   d = Double.parseDouble(br.readLine());
              System.out.println();
              ht.put(nm,d);
          }
      }
    
         
   
   
     void disp_record()
     {
         Enumeration names= ht.keys();
         //Returns an enumeration of the keys in this hashtable. <-=keys()
         while(names.hasMoreElements())     //Tests if this enumeration contains more elements.
         {
             nm=(String)names.nextElement();
                             //the next element of this enumeration.
 
              System.out.print(nm+" => "+ht.get(nm));
              //Returns the value to which the specified key is mapped in this hashtable.
              System.out.println();
         }
             System.out.println();
      }
  
     void highest_record()
     {
         Collection c=ht.values();
         //Object obj=Collections.max(c);
         //System.out.println("Highest Marks: "+obj);
         System.out.println("Highest Marks: "+Collections.max(c));
     }   
   
 }

Tuesday, August 7, 2012

LRU Page replacement Algorithm

Below is a C Program Which Explains the LRU Page replacement Algorithm in a Proper and Clear Way.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,reftime;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_lru_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].reftime<frames[selfno].reftime)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15,currtime;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].reftime=-1;
   }

   printf("\nPageNo     Page Frames          Page Fault");
   printf("\n-------------------------------------------");
   currtime=0;
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_lru_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].reftime=currtime;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : YES");
     }
    else//page found
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].reftime=currtime;
       for (fno=0; fno<n; fno++)
         printf("%4d",frames[fno].pno);
       printf(" : NO");
    }
       currtime++;
   }
  printf("\n------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

MFU Page Replacement Algorithm

Here is a C Program Which Explain the Working of MFU Page Replacement Algorithm in C.

#include<stdio.h>
#include<conio.h>
struct node
{
  int pno,freq;
}frames[20];
int n;

int page_found(int pno)
{
  int fno;
  for(fno=0;fno<n;fno++)
    if(frames[fno].pno==pno)
       return fno;
    return -1;
}

int get_free_frame()
{  int fno;
  for (fno=0; fno<=n; fno++)
    if (frames[fno].pno==-1)
        return(fno);
   return(-1);
}

int get_mfu_frame()
{
  int fno;
  int selfno=0;
  for (fno=1; fno<n; fno++)
    if(frames[fno].freq>frames[selfno].freq)
    selfno=fno;
  return selfno;
}
void main()
{
   int p_request[]={5,8,10,14,10,9,5,10,8,5,1,10,9,12,10};
   int size=15;
   int page_falts=0,i,j,fno;
   clrscr();
   printf("\nHow many frames:");  scanf("%d",&n);
   //initialize frames
   for (i=0; i<n; i++)
   { frames[i].pno=-1;
     frames[i].freq=0;
   }

   printf("\nPageNo     Page Frames              Page Fault");
   printf("\n---------------------------------------------------");
   for(i=0;i<size;i++)
   {
     j=page_found(p_request[i]);
     if(j==-1)  //page fault occurs
     {
       j=get_free_frame();
       if (j==-1) //no free frame - do page replacement
         j=get_mfu_frame();
       page_falts++;
       frames[j].pno=p_request[i];
       frames[j].freq=1;
       printf("\n%4d\t ",p_request[i]);
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : YES");
     }
    else //page found in frame j
    {
       printf("\n%4d\t ",p_request[i]);
       frames[j].freq++;
       for (fno=0; fno<n; fno++)
         printf("%4d:%2d",frames[fno].pno,frames[fno].freq);
       printf(" : NO");
    }
   }
  printf("\n-------------------------------------------------------");
  printf("\n Number of Page_Falts=%d",page_falts);
  getch();
}

C Program To Print Lines From File

Below Given Is a Simple Program which prints the lines of a file but with different user given instructions.

The Feature of the Program is as Follows:

The Program Prints,

1) print first 10 lines of file

2) print last  20 lines of file

3) print all lines of file


#include <stdio.h>
#include <conio.h>
#include <process.h>
void main(int argc, char *argv[])
{
    int tot_lines,cnt;
    char *ptr;
    if( argc != 3 )
    {
        printf("\nInvalid number of arguments\n");
        return;
    }
    if( *argv[1] == '+' || *argv[1] == '-')
    {
        tot_lines = count_lines(argv[2]);
        ptr = argv[1];
        ptr++;  // skip '+' or '-'
        cnt = atoi(ptr);
        if ( cnt > tot_lines)
        {
            printf("\nInvalid line count\n");
            return;
        }
    }
    if( *argv[1] == '+' ) // typeline +cnt fname
        print_top_lines(argv[2],cnt);
    else
    if( *argv[1] == '-' ) // typeline -cnt fname
        print_bottom_lines(argv[2],cnt,tot_lines);
    else if (*argv[1]=='a')
        print_all_lines(argv[2]);
     else
         printf("\nInvalid option...");
} // main

int count_lines( char *fname)
{
    int tot_lines,ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open file");
        return(-1);
    }
    tot_lines = 0;
    while (fgets(buff,80,fp)!=NULL)
       tot_lines++;
    tot_lines++;
    fclose(fp);
    return(tot_lines);
} // count lines


int print_all_lines( char *fname)
{
    int ch;
    FILE *fp;
    char buff[80];
    fp = fopen(fname,"r");
    printf("\n");
    while(fgets(buff,80,fp)!=NULL)
     printf("%s",buff);

    fclose(fp);
    return;
} // print all lines

int print_top_lines(char *fname, int cnt)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];

    curr_cnt = 0;

    fp = fopen(fname,"r");

    fgets(buff,80,fp);
    printf("\n");
    while( curr_cnt < cnt )
    {
        printf("%s",buff);
        fgets(buff,80,fp);
        curr_cnt++;
    }
    fclose(fp);
    return;
}
int print_bottom_lines(char *fname, int cnt, int tot_lines)
{
    int curr_cnt;
    int ch;
    FILE *fp;
    char buff[80];
    curr_cnt = 0;
    printf("\n");
    fp = fopen(fname,"r");
    while( 1)
    {
        fgets(buff,80,fp);
        curr_cnt++;
        if( curr_cnt >= tot_lines - cnt )
            break;
    }
    while( fgets(buff,80,fp) != NULL)
    {
        printf("%s", buff);
    }
    fclose(fp);
    return;
}

Shell Program For Searching a String.

Below is a Simple Shell Program in C Language which Implement search command as follows

1) search first occurrence of pattern in file name

2) count no of occurrences of pattern in file name

3) search all occurrences of pattern in file name


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


void main( int argc, char *argv[])
{
    char pattern[20],fname[20],option;

    printf("\nSearch Starts..");
    if( argc != 4 )
    {
        printf("\nInvalid number of arguments");
        return;
    }// if
    // set param
    option = *argv[1];
    strcpy(pattern,argv[2]);
    strcpy(fname,argv[3]);

    switch(option)
    {
        case 'f' :       find_first_occ(fname,pattern);
                        break;
        case 'c' :       count_all_occ(fname,pattern);
                        break;
        case 'a' :       print_all_occ(fname,pattern);
                        break;
        default  :        printf("\nInvalid option");
                        break;
    } // switch
} // main

int find_first_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr;
    int i,m,c,lineno;

    fp = fopen(fname,"r");
    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    lineno=0;
    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;

        ptr = strstr(str,pattern);
        if( ptr != NULL )
        {
            printf("\n lineno = %d : Line = %s", lineno,str);
            printf("\n position = %d", ptr - str +1 );
            break;
        }
    } // while
    fclose(fp);
    return;
} // find first occ


int count_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int count=0;

    int i,m,c,lineno;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);

        ptr1 = str;
        ptr = strstr(ptr1,pattern);

        while( ptr != NULL )
        {
            count++;
            ptr1= ptr+1;
            ptr = strstr(ptr1,pattern);
        }
    } // while
    fclose(fp);
    printf("\nPattern %s occurs %d times", pattern,count);
    return;
} // count all occ


int print_all_occ( char fname[], char pattern[])
{
    FILE *fp;
    char str[100],*ptr,*ptr1;
    int lineno=0;

    int i,m,c;

    fp = fopen(fname,"r");

    if( fp == NULL )
    {
        printf("\nUnable to open given file");
        return;
    }

    while ( !feof(fp))
    {
        strset(str,'\0');
        fgets(str,99,fp);
        lineno++;
        if( strstr(str,pattern) != NULL )
            printf("Line:%d: %s",lineno,str);

    } // while
    fclose(fp);
    return;
} // print all occurences

LOOK Algorithm using Disk Scheduling

Below is a Simple Program in C Language Which Explains Simulation of LOOK Algorithm of Disk Scheduling

#include <alloc.h>

struct reqblock
{ int block;
   struct reqblock *next;
} *first,*curr,*prev;

int n,currpos,headmove=0;
char direction;

void get_req_blocks();
 void scan();
void main()
{
  clrscr();
   printf("\nEnter total number of blocks in the disk:");
   scanf("%d",&n);
   printf("\nEnter request block numbers string terminated by -1\n");
    get_req_blocks();
    //print req string
    curr=first;
    while(curr!=NULL)
    { printf("%d\t",curr->block);
      curr=curr->next;
     }
     printf("\nEnter direction of head movement:(F-Forwad,B-Backward):");
     flushall(); scanf("%c",&direction);
      printf("\nEnter block no. as current head position:");
      scanf("%d",&currpos);
     scan();
     printf("\nNumber of headmovements:%d",headmove);
  }

  void get_req_blocks()
  { struct reqblock *t,*pt;
    int blockno;
    first=NULL;
    scanf("%d",&blockno);
    while(blockno!=-1)
    { curr=(struct reqblock *) malloc(sizeof(struct reqblock));
      curr->block=blockno;
      curr->next=NULL;
     if (first==NULL) //req str is empty
         first=curr;
     else
         prev->next=curr;
      prev=curr;
      scanf("%d",&blockno);
    }//while
  }

 void scan()
  {  int selblock;
     printf("\nList of request served:\n");

     while(first!=NULL)
     {
       if (!look())
         direction=(direction=='F')?'B':'F';
       selblock=get_next_block();
       if (selblock!=-1)
           printf("%d\t",selblock);
        if (direction=='F')
        {  if (currpos==n-1)
             direction='B';
         else
         {  currpos++; headmove++;
          }
      }
      else
      {
         if (currpos==0)
             direction='F';
         else
         { currpos--;  headmove++;}
       }
      }//while
      headmove--;
   }

 int look()
 {
   if (direction=='F')
   {  curr=first;
      while(curr!=NULL)
      {   if (curr->block>currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
   else //direction='B'
   {   curr=first;
      while(curr!=NULL)
      {  if (curr->block<currpos)
          return(1);
          curr=curr->next;
       }
       return(0);
     }
 }

 get_next_block()
   {
        int selblock;
         curr=first;
          while(curr->block!=currpos)
           {  prev=curr;
              curr=curr->next;
              if (curr==NULL) return(-1);
            }
            selblock=curr->block;
            if (curr==first)
               first=first->next;
             else
               prev->next=curr->next;
             free(curr);
            return(selblock);
  }

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...