Thursday, June 30, 2016

Calculation of First and Follow programs for Compiler Design Lab

Simulate First and Follow of a Grammar

First.c :

/*Assumptions:

Each Non terminal character is represented by one Uppercase letter.
Each Terminal character is represented by one lowercase letter.
LHS and RHS of each production will be separated by a "=" symbol.
There will be no Blank space within a production string. 
Assumed that Left recursion is avoided in all input productions. 
Use $ to represent epsilon  */

#include<stdio.h>
#include<ctype.h>
void FIRST(char[],char );
void addToResultSet(char[],char);
int numOfProductions;
char productionSet[10][10];
main()
{
    int i;
    char choice;
    char c;
    char result[20];
    printf("How many number of productions ? :");
    scanf(" %d",&numOfProductions);
    for(i=0;i<numOfProductions;i++)/*read production string eg: E=E+T*/
    {
        printf("Enter productions Number %d : ",i+1);
        scanf(" %s",productionSet[i]);
    }
    do
    {
        printf("\n Find the FIRST of  :");
        scanf(" %c",&c);
FIRST(result,c); /*Compute FIRST; Get Answer in 'result' array*/
        printf("\n FIRST(%c)= { ",c);
        for(i=0;result[i]!='\0';i++)
printf(" %c ",result[i]);       /*Display result*/
        printf("}\n");
         printf("press 'y' to continue : ");
        scanf(" %c",&choice);
    }
    while(choice=='y'||choice =='Y');
}
/*
 *Function FIRST:
 *Compute the elements in FIRST(c) and write them
 *in Result Array.
 */
void FIRST(char* Result,char c)
{
    int i,j,k;
    char subResult[20];
    int foundEpsilon;
    subResult[0]='\0';
    Result[0]='\0';
    /*If X is terminal, FIRST(X) = {X}.*/
    if(!(isupper(c)))
    {
        addToResultSet(Result,c);
               return ;
    }
    /*If X is non terminal
    /Read each production*/
    for(i=0;i<numOfProductions;i++)
    {
/*Find production with X as LHS*/
        if(productionSet[i][0]==c)
        {
/*If X =e is a production, then add e to FIRST(X).*/
 if(productionSet[i][2]=='#') addToResultSet(Result,'#');
   /*If X is a non-terminal, and X = Y1 Y2 … Yk
            is a production, then add a to FIRST(X)
            if for some i, a is in FIRST(Yi),
   and e is in all of FIRST(Y1), …, FIRST(Yi-1).*/
      else
            {
                j=2;
                while(productionSet[i][j]!='\0')
                {
                foundEpsilon=0;
                FIRST(subResult,productionSet[i][j]);
                for(k=0;subResult[k]!='\0';k++)
                    addToResultSet(Result,subResult[k]);
                 for(k=0;subResult[k]!='\0';k++)
                     if(subResult[k]=='#')
                     {
                         foundEpsilon=1;
                         break;
                     }
/*No e found, no need to check next element*/
                 if(!foundEpsilon)
                     break;
                 j++;
                }
            }
    }
}
    return ;
}
/* addToResultSet adds the computed
 *element to result set.
 *This code avoids multiple inclusion of elements
  */
void addToResultSet(char Result[],char val)
{
    int k;
    for(k=0 ;Result[k]!='\0';k++)
        if(Result[k]==val)
            return;
    Result[k]=val;
    Result[k+1]='\0';
}


Output:





Follow.c 


#include<stdio.h>
#include<ctype.h>
#include<string.h>
int n,m=0,p,i=0,j=0;
char a[10][10],followResult[10];
void follow(char c);
void first(char c);
void addToResult(char);
int main()
{
 int i;
 int choice;
 char c,ch;
 clrscr();
 printf("Enter the no.of productions: ");
scanf("%d", &n);
 printf(" Enter %d productions\nProduction with multiple terms should be give as separate productions \n", n);
 for(i=0;i<n;i++)
  scanf("%s%c",a[i],&ch);
    do
 {
  m=0;
  printf("Find FOLLOW of -->");
  scanf(" %c",&c);
  follow(c);
  printf("FOLLOW(%c) = { ",c);
  for(i=0;i<m;i++)
   printf("%c ",followResult[i]);
  printf(" }\n");
  printf("Do you want to continue(Press 1 to continue....)?");
 scanf("%d",&choice);
 }
 while(choice==1);
}
void follow(char c)
{
    if(a[0][0]==c)addToResult('$');
 for(i=0;i<n;i++)
 {
  for(j=2;j<strlen(a[i]);j++)
  {
   if(a[i][j]==c)
   {
    if(a[i][j+1]!='\0')first(a[i][j+1]);
    if(a[i][j+1]=='\0'&&c!=a[i][0])
     follow(a[i][0]);
   }
  }
 }
}
void first(char c)
{
      int k;
                 if(!(isupper(c)))
    /*f[m++]=c;  */
                     addToResult(c);
                 for(k=0;k<n;k++)
                 {
                 if(a[k][0]==c)
                 {
                 if(a[k][2]=='#') follow(a[i][0]);
                 else if(islower(a[k][2]))
    /*f[m++]=a[k][2];    */
                     addToResult(a[k][2]);
                 else first(a[k][2]);
                 }
                 }
}
void  addToResult(char c)
{
    int i;
    for( i=0;i<=m;i++)
        if(followResult[i]==c)
            return;
   followResult[m++]=c;
}

Output:



Labels:

Monday, June 27, 2016

advanced java program for client server communication using TCP (3rd program)

Aim:  Write java programs for TCP server and Client interaction as per given below.
              I) A program to create TCP server to send a message to client.
              II) A program to create TCP client to receive the message sent by the server.

Theory:
The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols:
  • TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
  • UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.
  • Socket Programming: This is most widely used concept in Networking and it has been explained in very detail.
  • URL Processing: This would be covered separately. Click here to learn about URL Processing in Java language.
Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
  • The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
  • The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
  • After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.
  • The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.
  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets.


Server1.java

import java.net.*;
import java.io.*;
public class Server1
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket s= new ServerSocket(95);
System.out.println("Server Waiting for the Client");
Socket cs=s.accept();
InetAddress ie=cs.getInetAddress();
String cli=ie.getHostAddress();
System.out.println("Connected to the client with IP "+cli);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
do
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.println("to  client  ");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("bye")||st==null)
break;
System.out.println("from client.  "+st);
}while(true);
in.close();
out.close();
cs.close();
}
catch(IOException e)
{
}

}
}


Client1.java

import java.net.*;
import java.io.*;
public class client1
{
public static void main(String args[])throws IOException
{
try
{
Socket con= new Socket("localhost",95);

BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("from server:"+s1);
System.out.println("enter the messages to the server");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("bye")||st==null)
break;

}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e)
{
}

}
}


Output:












Labels: