Compiler Design & Networks Lab Manual
Compiler Design & Networks Lab Manual
LIST OF EXPERIMENTS
EX.
No.
PAGE
DESCRIPTION
NO.
IMPLEMENTATION
EXPRESSION
11
16
22
28
32
36
41
10
45
OF
LEXICAL
ANALYZER
FOR
ARITHMETIC
CYCLE II (NETWORKS)
(A) TO FIND THE IP ADDRESS OF LOCAL HOST
49
51
12
53
13
57
14
60
15
63
16
66
11
Ex. No: 1
Date:
Token
*******
If
variable-name
numeric-constant
;
(
)
{
}
>
>=
<
<=
!
!=
=
==
<1,1>
<2,#address>
<3,#address>
<4,4>
<5,0>
<5,1>
<6,0>
<6,1>
<62,62>
<620,620>
<60,60>
<600,600>
<33,33>
<330,330>
<61,61>
<610,610>
Program:
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
char vars[100][100];
int vcnt;
char input[1000],c;
char token[50],tlen;
int state=0,pos=0,i=0,id;
3
char*getAddress(char str[])
{
for(i=0;i<vcnt;i++)
if(strcmp(str,vars[i])==0)
return vars[i];
strcpy(vars[vcnt],str);
return vars[vcnt++];
}
intisrelop(char c)
{
if(c=='>'||c=='<'||c=='|'||c=='=')
return 1;
else
return 0;
}
int main(void)
{
clrscr();
printf("Enter the Input String:");
gets(input);
do
{
c=input[pos];
putchar(c);
switch(state)
{
case 0:
if(c=='i')
state=1;
break;
case 1:
if(c=='f')
{
printf("\t<1,1>\n");
state =2;
}
break;
case 2:
if(isspace(c))
printf("\b");
if(isalpha(c))
{
token[0]=c;
tlen=1;
state=3;
}
if(isdigit(c))
state=4;
4
if(isrelop(c))
state=5;
if(c==';')printf("\t<4,4>\n");
if(c=='(')printf("\t<5,0>\n");
if(c==')')printf("\t<5,1>\n");
if(c=='{') printf("\t<6,1>\n");
if(c=='}') printf("\t<6,2>\n");
break;
case 3:
if(!isalnum(c))
{
token[tlen]='\o';
printf("\b\t<2,%p>\n",getAddress(token));
state=2;
pos--;
}
else
token[tlen++]=c;
break;
case 4:
if(!isdigit(c))
{
printf("\b\t<3,%p>\n",&input[pos]);
state=2;
pos--;
}
break;
case 5:
id=input[pos-1];
if(c=='=')
printf("\t<%d,%d>\n",id*10,id*10);
else
{
printf("\b\t<%d,%d>\n",id,id);
pos--;
}
state=2;
break;
}
pos++;
}
while(c!=0);
getch();
return 0;
}
<1,1>
<5,0>
<2,0960>
<620,620>
<2,09c4>
<5,1>
<2,0A28>
<61,61>
<2,0A8c>
<4,4>
Result:
The above C program was successfully executed and verified.
6
Ex. No: 2
Date:
Token
******
Variable name
Numeric constant
;
=
+
+=
-=
*
*=
/
/=
%
%=
^
^=
<1,#adddress>
<2,#address>
<3,3>
<4,4>
<43,43>
<430,430>
<45,45>
<450,450>
<42,42>
<420,420>
<47,47>
<470,470>
<37,37>
<370,370>
<94,94>
<940,940>
Program:
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
char vars[100][100];
int vcnt;
char input[1000],c;
char token[50],tlen;
int state=0,pos=0,i=0,id;
7
case 1:
if(!isalnum(c))
{
token[tlen]='\o';
printf("\b\t<1,%p>\n",getAddress(token));
state=0;
pos--;
}
else
token[tlen++]=c;
break;
case 2:
if(!isdigit(c))
{
printf("\b\t<2,%p>\n",&input[pos]);
state=0;
pos--;
}
break;
case 3:
id=input[pos-1];
if(c=='=')
printf("\t<%d,%d>\n",id*10,id*10);
else
{
printf("\b\t<%d,%d>\n",id,id);
pos--;
}
state=0;
break;
}
pos++;
}
while(c!=0);
getch();
return 0;
}
<1,08CE>
<4,4>
<1,08CE>
<42,42>
<2,04E9>
<43,43>
<1,0932>
<47,47>
<1,0996>
<3,3>
Result:
The above C program was successfully executed and verified.
10
Ex. No: 3
Date:
fo=fopen("inter.c","w");
fop=fopen("oper.c","r");
fk=fopen("key.c","r");
c=getc(fi);
while(!feof(fi))
{
if(isalpha(c)||isdigit(c)||(c=='['||c==']'||c=='.'==1))
fputc(c,fo);
else
{
if(c=='\n')
fprintf(fo,"\t$\t");
else
fprintf(fo,"\t%c\t",c);
}
c=getc(fi);
}
fclose(fi);
fclose(fo);
fi=fopen("inter.c","r");
printf("\n Lexical Analysis");
fscanf(fi,"%s",a);
printf("\n Line: %d\n",i++);
while(!feof(fi))
{
if(strcmp(a,"$")==0)
{
printf("\n Line: %d \n",i++);
fscanf(fi,"%s",a);
}
fscanf(fop,"%s",ch);
while(!feof(fop))
{
if(strcmp(ch,a)==0)
{
fscanf(fop,"%s",ch);
printf("\t\t%s\t:\t%s\n",a,ch);
flag=1;
}
fscanf(fop,"%s",ch);
}
rewind(fop);
fscanf(fk,"%s",ch);
while(!feof(fk))
{
if(strcmp(ch,a)==0)
{
12
fscanf(fk,"%k",ch);
printf("\t\t%s\t:\tKeyword\n",a);
flag=1;
}
fscanf(fk,"%s",ch);
}
rewind(fk);
if(flag==0)
{
if(isdigit(a[0]))
printf("\t\t%s\t:\tConstant\n",a);
else
printf("\t\t%s\t:\tIdentifier\n",a);
}
flag=0;
fscanf(fi,"%s",a);
}
getch();
}
Key.C:
int
void
main
char
if
for
while
else
printf
scanf
FILE
include
stdio.h
conio.h
iostream.h
Oper.C:
( open para
) closepara
{ openbrace
} closebrace
< lesser
> greater
" doublequote
' singlequote
13
: colon
; semicolon
# preprocessor
= equal
== asign
% percentage
^ bitwise
& reference
* star
+ add
- sub
\ backslash
/ slash
Input.C:
#include "stdio.h"
#include "conio.h"
void main()
{
int a=10,b,c;
a=b*c;
getch();
}
Sample Input & Output:
Enter the File Name: Input.C
Line: 1
# : Preprocessor
include : keyword
< : lesser
stdio.h : keyword
> : greater
Line: 2
# : Preprocessor
include : keyword
< : lesser
conio.h : keyword
> : greater
Line: 3
void : keyword
14
main : keyword
( : openpara
) : closepara
Line: 4
{ : openbrace
Line: 5
int : keyword
a : identifier
= : equal
10 : constant
, : identifier
b : identifier
, : identifier
c : identifier
; : semicolon
Line: 6
a : identifier
= : equal
b : identifier
* : star
c : identifier
; : semicolon
Line: 8
} : closebrace
Result:
The above C program was successfully executed and verified.
15
Ex. No: 4
Date:
outtextxy((*x2-*x1)/2+*x1,*y1+30,pr);
ellipse(*x1+(*x2-*x1)/2,*y2+10,180,360,(*x2-*x1)/2+40,70);
outtextxy(*x2+37,*y2+14,"^");
if(*x1-40<minx)minx=*x1-40;
miny=*y1;
}
void star1(int *x1,int *y1,int *x2,int *y2)
{
char pr[10];
ellipse(*x1+(*x2-*x1)/2+15,*y2-10,0,180,(*x2-*x1)/2+15,70);
outtextxy(*x1-2,*y2-17,"v");
line(*x2+40,*y2,*x2+60,*y2);
outtextxy(*x1-15,*y1-3,">");
circle(*x1-40,*y1,10);
line(*x1-30,*y2,*x1-10,*y2);
outtextxy(*x2+25,*y2-3,">");
sprintf(pr,"%c",238);
outtextxy(*x2+15,*y2-9,pr);
outtextxy(*x1-25,*y1-9,pr);
outtextxy((*x2-*x1)/2+*x1,*y1-30,pr);
outtextxy((*x2-*x1)/2+*x1,*y1+30,pr);
ellipse(*x1+(*x2-*x1)/2+15,*y2+10,180,360,(*x2-*x1)/2+50,70);
outtextxy(*x2+62,*y2+13,"^");
if(*x1-40<minx)minx=*x1-40;
miny=*y1;
}
void basis(int *x1,int *y1,char x)
{
char pr[5];
circle(*x1,*y1,10);
line(*x1+30,*y1,*x1+10,*y1);
sprintf(pr,"%c",x);
outtextxy(*x1+20,*y1-10,pr);
outtextxy(*x1+23,*y1-3,">");
circle(*x1+40,*y1,10);
if(*x1<minx)minx=*x1;
miny=*y1;
}
void slash(int *x1,int *y1,int *x2,int *y2,int *x3,int *y3,int *x4,int *y4)
{
char pr[10];
int c1,c2;
c1=*x1;
if(*x3>c1)c1=*x3;
c2=*x2;
if(*x4>c2)c2=*x4;
line(*x1-10,*y1,c1-40,(*y3-*y1)/2+*y1-10);
17
outtextxy(*x1-15,*y1-3,">");
outtextxy(*x3-15,*y4-3,">");
circle(c1-40,(*y4-*y2)/2+*y2,10);
sprintf(pr,"%c",238);
outtextxy(c1-40,(*y4-*y2)/2+*y2+25,pr);
outtextxy(c1-40,(*y4-*y2)/2+*y2-25,pr);
line(*x2+10,*y2,c2+40,(*y4-*y2)/2+*y2-10);
line(*x3-10,*y3,c1-40,(*y3-*y1)/2+*y2+10);
circle(c2+40,(*y4-*y2)/2+*y2,10);
outtextxy(c2+40,(*y4-*y2)/2+*y2-25,pr);
outtextxy(c2-40,(*y4-*y2)/2+*y2+25,pr);
outtextxy(c2+35,(*y4-*y2)/2+*y2-15,"^");
outtextxy(c1+35,(*y4-*y2)/2+*y2+10,"^");
line(*x4+10,*y2,c2+40,(*y4-*y2)/2+*y2+10);
minx=c1-40;
miny=(*y4-*y2)/2+*y2;
}
void main()
{
int d=0,l,x1=200,y1=200,len,par=0,op[10];
int cx1=200,cy1=200,cx2,cy2,cx3,cy3,cx4,cy4;
char str[20];
int gd=DETECT,gm;
int stx[20],endx[20],sty[20],endy[20];
int pos=0,i=0;
clrscr();
initgraph(&gd,&gm,"c:\\dosapp\\tcplus\\bgi");
printf("\n enter the regular expression:");
scanf("%s",str);
len=(strlen(str));
while(i<len)
{
if(isalpha(str[i]))
{
if(str[i+1]=='*')x1=x1+40;
basis(&x1,&y1,str[i]);
stx[pos]=x1;
endx[pos]=x1+40;
sty[pos]=y1;
endy[pos]=y1;
x1=x1+40;
pos++;
}
if(str[i]=='*')
{
star(&stx[pos-1],&sty[pos-1],&endx[pos-1],&endy[pos-1]);
stx[pos-1]=stx[pos-1]-40;
18
endx[pos-1]=endx[pos-1]+40;
x1=x1+40;
}
if(str[i]=='(')
{
int s;
s=i;
while(str[s]!=')')s++;
if((str[s+1]=='*')&&(pos!=0))x1=x1+40;
op[par]=pos;
par++;
}
if(str[i]==')')
{
cx2=endx[pos-1];
cy2=endy[pos-1];
l=op[par-1];
cx1=stx[1];
cx2=sty[1];
par--;
if(str[i+1]=='*')
{
i++;
star1(&cx1,&cy1,&cx2,&cy2);
cx1=cx1-40;
cx2=cx2+40;
stx[1]=stx[1]-40;
endx[pos-1]=endx[pos-1]+40;
x1=x1+40;
}
if(d==1)
{
slash(&cx3,&cy3,&cx4,&cy4,&cx1,&cy1,&cx2,&cy2);
if(cx4>cx2)x1=cx4+40;
else x1=cx2+40;
y1=(y1-cy4)/2.0+cy4;
d=0;
}
}
if(str[i]=='/')
{
cx2=endx[pos-1];
cy2=endy[pos-1];
x1=200;
y1=y1+100;
19
if(str[i+1]=='(')
{
d=1;
cx3=cx1;
cy3=cy1;
cx4=cx2;
cy4=cy2;
}
if(isalpha(str[i+1]))
{
i++;
basis(&x1,&y1,str[i]);
stx[pos]=x1;
endx[pos]=x1+40;
sty[pos]=y1;
endy[pos]=y1;
if(str[i+1]=='*')
{
i++;
star(&stx[pos],&sty[pos],&endx[pos],&endy[pos]);
stx[pos]=stx[pos]-40;
endx[pos]=endx[pos]+40;
}
slash(&cx1,&cy1,&cx2,&cy2,&stx[pos],&sty[pos],&endx[pos],&endy[pos]);
if(cx2>endx[pos])x1=cx2+40;
else x1=endx[pos]+40;
y1=(y1-cy2)/2.0+cy2;
cx1=cx1-40;
cy1=(sty[pos]-cy1)/2.0+cy1;
cx2=cx2+40;
cy2=(endy[pos]-cy2)/2.0+cy2;
l=op[par-1];
stx[1]=cx1;
sty[1]=cy1;
endx[pos]=cx2;
endy[pos]=cy2;
pos++;
}
}
i++;
}
circle(x1,y1,13);
line(minx-30,miny,minx-10,miny);
outtextxy(minx-100,miny-10,"start");
outtextxy(minx-15,miny-3,">");
20
getch();
closegraph();
}
Sample Input & Output:
Result:
The above C program was successfully executed and verified.
21
Ex.No: 5
Date:
return(a);
}
void epi_close(int s1,int s2,int c)
{
int i,k,f;
for(i=1;i<=n;i++)
{
if(data[s2][i]=='e')
{
f=0;
for(k=1;k<=c;k++)
if(e_close[s1][k]==i)
f=1;
if(f==0)
{
c++;
e_close[s1][c]=i;
push(i);
}
}
}
while(s.top!=0) epi_close(s1,pop(),c);
}
int move(int sta,char c)
{
int i;
for(i=1;i<=n;i++)
{
if(data[sta][i]==c)
return(i);
}
return(0);
}
void e_union(int m,int n)
{
int i=0,j,t;
for(j=1;mark[m][i]!=-1;j++)
{
while((mark[m][i]!=e_close[n][j])&&(mark[m][i]!=-1))
i++;
if(mark[m][i]==-1)mark[m][i]=e_close[n][j];
}
}
void main()
{
int i,j,k,Lo,m,p,q,t,f;
clrscr();
23
j=1;
while(e_close[1][j]!=-1)
{
mark[1][j]=e_close[1][j];
j++;
}
st=1;
printf("\n DFA Table is:");
printf("\n
a
b
");
printf("\n--------------------------------------");
for(i=1;i<=st;i++)
{
printf("\n{");
for(j=1;mark[i][j]!=-1;j++)
printf("%d",mark[i][j]);
printf("}");
while(j<7)
{
printf(" ");
j++;
}
for(Lo=1;Lo<=2;Lo++)
{
for(j=1;mark[i][j]!=-1;j++)
{
if(Lo==1)
t=move(mark[i][j],'a');
if(Lo==2)
t=move(mark[i][j],'b');
if(t!=0)
e_union(st+1,t);
}
for(p=1;mark[st+1][p]!=-1;p++)
for(q=2;mark[st+1][q]!=-1;q++)
{
if(mark[st+1][q-1]>mark[st+1][q])
{
t=mark[st+1][q];
mark[st+1][q]=mark[st+1][q-1];
mark[st+1][q-1]=t;
}
}
f=1;
for(p=1;p<=st;p++)
{
j=1;
25
while((mark[st+1][j]==mark[p][j])&&(mark[st+1][j]!=-1))
j++;
if(mark[st+1][j]==-1 && mark[p][j]==-1)
f=0;
}
if(mark[st+1][1]==-1)
f=0;
printf("\t{");
for(j=1;mark[st+1][j]!=-1;j++)
{
printf("%d",mark[st+1][j]);
}
printf("}\t");
if(Lo==1)
printf(" ");
if(f==1)
st++;
if(f==0)
{
for(p=1;p<=30;p++)
mark[st+1][p]=-1;
}
}
}
getch();
}
26
Result:
The above C program was successfully executed and verified.
27
Ex.No: 6
Date:
Input Symbol
Action
id1*id2$
shift
$id1
*id2 $
shift *
$*
id2$
shift id2
$id2
shift
accept
28
Program:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
void check();
void main()
{
clrscr();
printf("\n\n\t Shift Reduce Parser\n");
printf("\n\t***** ****** ******");
printf("\n Grammar\n\n");
printf("E->E+E\nE->E/E\n");
printf("E->E*E\nE->a/b");
printf("\n Enter the Input Symbol:\t");
gets(ip_sym);
printf("\n\n\t Stack Implementation Table");
printf("\n Stack\t\t Input Symbol\t\t Action");
printf("\n $\t\t %s$\t\t\t --",ip_sym);
strcpy(act,"shift");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
len=strlen(ip_sym);
for(i=0;i<=len-1;i++)
{
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]=' ';
ip_ptr++;
printf("\n$%s\t\t%s$\t\t\t%s",stack,ip_sym,act);
strcpy(act,"shift");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
check();
st_ptr++;
}
st_ptr++;
check();
getch();
}
29
void check()
{
int flag=0;
temp2[0]=stack[st_ptr];
temp[1]='\0';
if((!strcmpi(temp2,"a"))||(!strcmpi(temp2,"b")))
{
stack[st_ptr]='E';
if(!strcmpi(temp2,"a"))
printf("\n$%s\t\t%s$\t\t\tE->a",stack,ip_sym);
else
printf("\n$%s\t\t%s$\t\t\tE->a",stack,ip_sym);
flag=1;
}
if((!strcmpi(temp2,"+"))||(strcmpi(temp2,"*"))||(!strcmpi(temp2,"/")))
{
flag=1;
}
if((!strcmpi(stack,"E+E"))||(!strcmpi(stack,"E/E"))||(!strcmpi(stack,"E*E")))
{
strcpy(stack,"E");
st_ptr=0;
if(!strcmpi(stack,"E+E"))
printf("\n$%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
else
if(!strcmpi(stack,"E/E"))
printf("\n$%s\t\t\t%s$\t\tE->E/E",stack,ip_sym);
else
printf("\n$%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
flag=1;
}
if(!strcmpi(stack,"E")&&ip_ptr==len)
{
printf("\n$%s\t\t%s$\t\t\tAccept",ip_sym);
getch();
exit(0);
}
if(flag==0)
{
printf("\n %s \t\t\t %s \t\t Reject",stack,ip_sym);
}
return;
}
30
if(a*b)
Input Symbol
if(a*b)$
f(a*b)$
(a*b)$
a*b)$
*b)$
*b)$
b)$
b)
Action
-shift i
shift f
shift (
shift a
E->a
shift *
reject
Result:
The above C program was successfully executed and verified.
31
Ex.No: 7
Date:
{'<','<','<','<','<','<','=','<','E' },
{'>','>','>','>','>','E','>','E','>' },
{'>','>','>','>','>','E','>','E','>' },
{'<','<','<','<','<','<','E','<','A' }
};
char s[30],st[30],qs[30];
int top=-1,r=-1,p=0;
void push(char a)
{
top++;
st[top]=a;
}
char pop()
{
char a;
a=st[top];
top--;
return a;
}
int find(char a)
{
switch(a)
{
case '+':return 0;
case '-':return 1;
case '*':return 2;
case '/':return 3;
case '^':return 4;
case '(':return 5;
case ')':return 6;
case 'a':return 7;
case '$':return 8;
default :return -1;
}
}
void display(char a)
{
printf("\n Shift %c",a);
}
void display1(char a)
{
if(isalpha(a))
printf("\n Reduce E->%c",a);
else if((a=='+')||(a=='-')||(a=='*')||(a=='/')||(a=='^'))
printf("\n Reduce E->E%cE",a);
else if(a==')')
printf("\n Reduce E->(E)");
33
}
intrel(char a,char b,char d)
{
if(isalpha(a)!=0)
a='a';
if(isalpha(b)!=0)
b='a';
if(q[find(a)][find(b)]==d)
return 1;
else
return 0;
}
void main()
{
char s[100];
int i=-1;
clrscr();
printf("\n\t Operator Preceding Parser\n");
printf("\n Enter the Arithmetic Expression End with $..");
gets(s);
push('$');
while(i)
{
if((s[p]=='$')&&(st[top]=='$'))
{
printf("\n\nAccepted");
break;
}
else if(rel(st[top],s[p],'<')||rel(st[top],s[p],'='))
{
display(s[p]);
push(s[p]);
p++;
}
else if(rel(st[top],s[p],'>'))
{
do
{
r++;
qs[r]=pop();
display1(qs[r]);
}
while(!rel(st[top],qs[r],'<'));
}
}
getch();
}
34
Result:
The above C program was successfully executed and verified.
35
Ex.No: 8
Date:
Tprime();
print T->FT';
end;
procedureTprime();
ifip_sym='*' then
begin
advance();
F();
Tprime()
print T'->T*FT'
end
else print T'->e
procedure F()
ifip_sym =id then
begin
advance();
print->id
end
else
Error();
end;
else
Error();
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
char ip_sym[15],ip_ptr=0;
void e_prime();
void t();
void e();
void t_prime();
void f();
void advance();
void e()
{
printf("\n\t\tE'------->TE'");
t();
e_prime();
}
void e_prime()
{
37
if(ip_sym[ip_ptr]=='+')
{
printf("\n\t\tE'------->+TE'");
advance();
t();
e_prime();
}
else
printf("\n\t\tE'----->e'");
}
void t()
{
printf("\n\t\tT'------->FT'"); f();
t_prime();
}
void t_prime()
{
if(ip_sym[ip_ptr]=='*')
{
printf("\n\t\tT------>*FT'"); advance();
f();
t_prime();
}
else
{
printf("\n\t\tT'----->e");
}
}
void f()
{
if((ip_sym[ip_ptr]=='i')||(ip_sym[ip_ptr]=='j'))
{
printf("\n\t\tF------>i"); advance();
}
else
{
if(ip_sym[ip_ptr]=='(')
{
advance();
e();
if(ip_sym[ip_ptr]==')')
{
advance();
printf("\n\t\tF----->(E)");
}
38
else
{
printf("\n\t\tSyntax Error");
getch();
exit(1);
}
}
}
}
void advance()
{
ip_ptr++;
}
void main()
{
int i;
clrscr();
printf("\n\t\tGRAMMER WITHOUT RECURSION");
printf("\n\t\tE------>TE'\n\t\tE'/e\r\t\tT----->FT");
printf("\n\t\tT------>*FT/e\n\t\tF------>(E)/id");
printf("\n\t\tEnter the Input Symbol: ");
gets(ip_sym);
printf("\n\t\tSequence of Production Rules");
e();
getch();
}
39
Result:
The above C program was successfully executed and verified.
40
Ex.No: 9
Date:
for(i=0;i<n-1;i++)
{
temp=op[i].l;
for(j=0;j<n;j++)
{
p=strchr(op[j].r,temp);
if(p)
{
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i].r);
z++;
}
}
}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");
for(k=0;k<z;k++)
{
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++)
{
tem=pr[m].r;
for(j=m+1;j<z;j++)
{
p=strstr(tem,pr[j].r);
if(p)
{
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++)
{
l=strchr(pr[i].r,t) ;
if(l)
{
a=l-pr[i].r;
printf("pos: %d",a);
pr[i].r[a]=pr[m].l;
}
}
}
}
}
42
43
Result:
The above C program was successfully executed and verified.
44
Ex.No: 10
Date:
Start
Get address code sequence.
Determine current location of 3 using address (for 1st operand).
If current location not already exist generate move (B,O).
Update address of A(for 2nd operand).
If current value of B and () is null,exist.
If they generate operator () A,3 ADPR.
Store the move instruction in memory
Stop.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<graphics.h>
typedef struct
{
char var[10];
int alive;
}
regist;
regist preg[10];
void substring(char exp[],int st,int end)
{
int i,j=0;
char dup[10]="";
for(i=st;i<end;i++)
dup[j++]=exp[i];
dup[j]='0';
45
strcpy(exp,dup);
}
int getregister(char var[])
{
int i;
for(i=0;i<10;i++)
{
if(preg[i].alive==0)
{
strcpy(preg[i].var,var);
break;
}
}
return(i);
}
void getvar(char exp[],char v[])
{
int i,j=0;
char var[10]="";
for(i=0;exp[i]!='\0';i++)
if(isalpha(exp[i]))
var[j++]=exp[i];
else
break;
strcpy(v,var);
}
void main()
{
char basic[10][10],var[10][10],fstr[10],op;
int i,j,k,reg,vc,flag=0;
clrscr();
printf("\nEnter the Three Address Code:\n");
for(i=0;;i++)
{
gets(basic[i]);
if(strcmp(basic[i],"exit")==0)
break;
}
printf("\nThe Equivalent Assembly Code is:\n");
for(j=0;j<i;j++)
{
getvar(basic[j],var[vc++]);
strcpy(fstr,var[vc-1]);
substring(basic[j],strlen(var[vc-1])+1,strlen(basic[j]));
getvar(basic[j],var[vc++]);
reg=getregister(var[vc-1]);
46
if(preg[reg].alive==0)
{
printf("\nMov R%d,%s",reg,var[vc-1]);
preg[reg].alive=1;
}
op=basic[j][strlen(var[vc-1])];
substring(basic[j],strlen(var[vc-1])+1,strlen(basic[j]));
getvar(basic[j],var[vc++]);
switch(op)
{
case '+': printf("\nAdd"); break;
case '-': printf("\nSub"); break;
case '*': printf("\nMul"); break;
case '/': printf("\nDiv"); break;
}
flag=1;
for(k=0;k<=reg;k++)
{
if(strcmp(preg[k].var,var[vc-1])==0)
{
printf("R%d, R%d",k,reg);
preg[k].alive=0;
flag=0;
break;
}
}
if(flag)
{
printf(" %s,R%d",var[vc-1],reg);
printf("\nMov %s,R%d",fstr,reg);
}
strcpy(preg[reg].var,var[vc-3]);
getch();
}
}
47
Result:
The above C program was successfully executed and verified.
48
Ex.No: 11 (A)
Date:
49
Result:
Thus the above Java Program was successfully executed and verified.
50
Ex.No:11(B)
Date:
Result:
Thus the above Java Program was successfully executed and verified.
52
Ex.No:12
Date:
try
{
sock = new ServerSocket(4000);
System.out.println("Server Ready");
client = sock.accept();
System.out.println("Client Connected");
fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ((line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}
54
Result:
Thus data from client to server is echoed back to the client to check reliability/noise
level of the channel.
56
Ex. No: 13
Date:
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com", "google.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19", "80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}
UDP DNS Client -- udpdnsclient.java
import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if(args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
58
Result:
Thus domain name requests by the client are resolved into their respective logical
address using lookup method.
59
Ex.No: 14
Date:
Send and Receive Message between Client and Server using TCP
Aim:
To write a Java program to send and receive message between Client and Server
using TCP.
Class:
ServerSocket:
This class implements server sockets. A server socket waits for requests to come in
over the network. It performs some operation based on that request, and then possibly returns
a result to the requester.
Methods:
ServerSocket()
ServerSocket(int port)
accept()
getInetAddress()
getLocalPart()
close()
Program:
Client:
import java.net.*;
import java.io.*;
import java.lang.*;
public class ex14client
{
public static void main(String args[])throws IOException
{
InetAddress a=InetAddress.getLocalHost();
Socket soc=new Socket(a,8888);
60
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter out =new PrintWriter(new BufferedWriter(new
OutputStreamWriter(soc.getOutputStream())),true);
for(int i=0;i<5;i++)
{
out.println("lines#"+i);
String str=in.readLine();
System.out.println(str);
}
out.println("end");
}
finally
{
System.out.println("closing");
soc.close();
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.lang.*;
public class ex14server
{
public static final int PORT=8888;
public static void main(String args[ ]) throws IOException
{
ServerSocket s=new ServerSocket(PORT);
try
{
Socket soc=s.accept( );
try
{
System.out.println("Connection accepted.....");
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter out =new PrintWriter(new BufferedWriter(new
OutputStreamWriter(soc.getOutputStream())),true);
while(true)
{
String str=in.readLine();
if(str.equals("end"))
61
break;
System.out.println("'echoing .."+str);
out.println(str);
}
}
finally
{
System.out.println("closing");
soc.close();
}
}
finally
{
s.close();
}
}
}
Sample Input & Output:
Client:
D:\Program Files\Java\jdk1.6.0_20\bin>javacex14client.java
D:\Program Files\Java\jdk1.6.0_20\bin> java ex14client
Connection accepted.....
'echoing ..lines#0
'echoing ..lines#1
'echoing ..lines#2
'echoing ..lines#3
'echoing ..lines#4
closing
Server:
D:\Program Files\Java\jdk1.6.0_20\bin>javacex14server.java
D:\Program Files\Java\jdk1.6.0_20\bin> java ex14server
lines#0
lines#1
lines#2
lines#3
lines#4
closing
Result:
Thus the above Java Program was successfully executed and verified.
62
Ex.No: 15
Date:
Send and Receive Message between Client and Server using UDP
Aim:
To write a Java program to send and receive message between Client and Server
using UDP.
Class:
DatagramSocket:
This class represents a socket for sending and receiving datagram packets. A
datagram socket is the sending or receiving point for a packet delivery service. Each packet
sent or received on a datagram socket is individually addressed and routed. Multiple packets
sent from one machine to another may be routed differently, and may arrive in any order.
User Datagram Protocol (UDP) broadcasts always enabled on a DatagramSocket. In order to
receive broadcast packets a DatagramSocket should be bound to the wildcard address. In
some implementations, broadcast packets may also be received when a DatagramSocket is
bound to a more specific address.
DatagramPacket:
Datagram packets are used to implement a connectionless packet delivery service.
Multiple packets sent from one machine to another might be routed differently, and might
arrive in any order. Packet delivery is not guaranteed.
Methods:
DatagramSocket(int port)
receive(DatagramPacket p)
send(DatagramPacket p)
DatagramPacket(byte[] buf, int length)
Constructs a
DatagramPacket for
receiving packets of length.
Constructs a datagram packet for sending
packets of length to the specified port
number on the specified host.
getData()
63
Program:
Client:
import java.net.*;
import java.io.*;
import java.lang.*;
public class ex15client
{
public static void main(String args[]) throws IOException
{
byte[] buff=new byte[512];
DatagramSocket soc=new DatagramSocket();
String s="HELLO SERVER-FROM CLIENT";
buff=s.getBytes();
InetAddress a=InetAddress.getLocalHost();
DatagramPacket pac=new DatagramPacket(buff,buff.length,a,8888);
soc.send(pac);
System.out.println("End of Sending");
byte[] buff1=new byte[512];
pac=new DatagramPacket(buff,buff1.length);
soc.receive(pac);
String messg=new String(pac.getData());
System.out.println(messg);
System.out.println("End Of Sending ");
}
}
Server:
import java.io.*;
import java.net.*;
import java.lang.*;
public class ex15server
{
public static void main(String args[]) throws IOException
{
byte[ ] buff=new byte[512];
DatagramSocket soc=new DatagramSocket(8888);
DatagramPacket pac=new DatagramPacket(buff,buff.length);
System.out.println("Server started ");
soc.receive(pac);
String msg=new String(pac.getData());
System.out.println(msg);
System.out.println("End of Reception");
String s="FROM SERVER HELLO CLIENT";
byte[ ] buff1=new byte[512];
buff1 =s.getBytes();
64
InetAddress a=pac.getAddress();
int port=pac.getPort();
pac=new DatagramPacket(buff,buff1.length,a,port);
soc.send(pac);
System.out.println("End of Sending");
}
}
Sample Input & Output:
Server:
D:\Program Files\Java\jdk1.6.0_20\bin>javac ex15server.java
D:\Program Files\Java\jdk1.6.0_20\bin> java ex15server
Server started
HELLO SERVER-FROM CLIENT
End of Reception
End of Sending
Client:
D:\Program Files\Java\jdk1.6.0_20\bin>javac ex15client.java
D:\Program Files\Java\jdk1.6.0_20\bin> java ex15client
End of Sending
Result:
Thus the above Java Program was successfully executed and verified.
65
Ex.No: 16
Date:
An application uses a data output stream to write data that can later be read by a
data input stream.
DataInputStream is not necessarily safe for multithreaded access. Thread safety is
optional and is the responsibility of users of methods in this class.
ii)
PrintStream:
Class adds functionality to another output stream, the ability to print representations
of various data values conveniently.
Program:
Sender:
import java.io.*;
import java.net.*;
import java.rmi.*;
public class sender
{
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(10);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
do
{
p=new PrintStream(s.getOutputStream());
66
Receiver:
import java.io.*;
import java.net.*;
public class receiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuff[]=new String[8];
String ch;
System.out.println();
67
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuff[rptr]=in.readLine();
System.out.println("The Received Frame "+rptr+"is:"+rbuff[rptr]);
}
rws-=nf;
System.out.println("\n Acknowledgement Send\n");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
68
Result:
Thus the above Java Program was successfully executed and verified.
69