You are on page 1of 73

CHINMAYAINSTITUTEOFTECHNOLOGY KANNUR

LABORATORYRECORD MCATHIRDSEMESTER(20102011) SCHOOLOFCOMPUTERSCIENCE AND INFORMATIONTECHNOLOGY


CHINMAYAINSTITUTEOFTECHNOLOGY KANNUR

CERTIFICATE
Certified that this is the bonafide record of the practical work done in_________________________________________________laboratory by___________________ ,University Register No__________________ of the Department of Master of Computer Applications , in partial fulfillmentoftherequirementasasubjectundertheUniversityofKannur duringthe________Semesterintheyear_____________. ExternalExaminer 1. 2. Place: Date: FacultyinCharge

INDEX
NETWORKPROGRAMMINGANDADMINISTRATION S.NO 1 PROGRAMS Createaparentandchildprocessusingfork() command.Theparentprocessprintsnevennumbers(nis readfromtheuser)andchildprocessprintsnodd numbers. Createaparentandchildprocessusingfork() command.Thechildprocessreadsafilenameandsends ittoparentthroughpipe.Theparentprocessrenamesthe fileafterreadingnewfilenamefromuser Implementaclientserverusingnamedpipes(FIFO).The clientsendsafilenametoserver.Theserversendsthe contentsofthefilebacktotheclientwhichprintsit. Implementtheaboveprogramusingpipesandfork(). Modifytheaboveprogramtoimplementafilecopy programusingFIFO.Theclientsendsthefilenameto server.Theserversendsthecontentstoclientandclient copiesittoafile. Writeaprogramtosendandreceivemessageusing sharedmemory. Writeaprogramtoprintthesharedmemoryinformation Writeaprogramtosendandreceivemessageusing messagequeues. CreateprogramstoimplementTCPclientandserver. Theclientandservershouldbeabletoexchange messages. ImplementaUDPclientandserver.Theclientshouldbe abletoexchangemessageswiththeserver. ImplementasimpleDNSclientandserverusingUDP Socketprogramming. ImplementasimpleFTPclientandserver DATE PGNO

4 5

6 7 8 9

10 11 12

INDEX
ASSEMBLYLANGUAGEPROGRAMMING S.NO 1 2 3 4 5 6 7 8 9 PROGRAMS INTRODUCTION TO 8086 Program to display a character on the screen. Program to display a string on the screen. Program to read a character from the keyboard and display it on the screen. Program to display a string on the screen using DOS call function 02h. Program to read a string from keyboard and disply it on the screen using DOS call function 02h. Program to read a string from keyboard and disply it on the screen using DOS call function 09h Program to read data from keyboard using BIOS function 00h Program to display a string on the screen implement using macros. Program to read a string from keyboard using DOS call function 01h and display it using 02h, implement using macros. Program to check whether the number is palindrome or not. Program to check whether the number is odd or even. Program to find sum of n numbers. Program to find largest of N numbers. Implement an application using ALP to reverse an entered string. Write an ALP to perform linear search on an array. Write an ALP to perform sort on an array. DATE PG.NO

10 11 12 13 14 15 16

INDEX
LEXPROGRAMS S.NO 1 2 3 PROGRAMS write a lex program to recognize integers. write a lex program to reognize floatingpoint numbers. Write a lex program to recognize identifiers. An identifier should start with a letter and may be followed by letters or digits. Write a lex program to recognize strings ending with "abb". Write a lex program to recognize strings containing odd number of 1's. Write a lex program to select only lines that begin with // and ignore all others. Write a lex program that converts or display the hexa equivalent of a decimal number. Write a lex program that displays the numbers for roman letters. Write a lex program to count number of lines,words and characters. PG.NO

4 5 6 7 8 9

NETWORKPROGRAMMING AND ADMINISTRATION

1.Createaparentandchildprocessusingfork()command.Theparentprocessprintsneven numbers(nisreadfromtheuser)andchildprocessprintsnoddnumbers. PROGRAM #include<stdio.h> main() { intid,n,i,j=2,k=1; printf("ENTERALIMIT\n"); scanf("%d",&n); id=fork(); if(id>0) { printf("PARENTPROCESSID:%d\n",getpid()); //printf("PARENTPROCESSID:%d\n",getppid()); printf("%dEVENNOSARE:\n",n); for(i=0;i<n;i++){ printf("%d\t",j); j=j+2; } printf("\n"); } else { printf("CHILDPROCESSID:%d\n",getpid()); printf("%dODDNOSARE:\n",n); for(i=0;i<n;i++){ printf("%d\t",k); k=k+2; } printf("\n"); } } OUTPUT ENTERALIMIT 5 CHILDPROCESSID:4835 5ODDNOSARE: 1 3 5 7 9 PARENTPROCESSID:4834 5EVENNOSARE: 2 4 6 8 10

2.Createaparentandchildprocessusingfork()command.Thechildprocessreadsafile nameandsendsittoparentthroughpipe.Theparentprocessrenamesthefileafterreading newfilenamefromuser PROGRAM #include<stdio.h> #include<stdlib.h> main() { intp[2],pid; charmsg[15],msg1[15]; pipe(p); pid=fork(); if(pid>0) { close(p[1]); read(p[0],msg1,15); printf("FILENAMESENTBYCHILD:%s\n",msg1); printf("ENTERANEWFILENAME\n"); scanf("%s",msg); if(rename(msg1,msg)==0) printf("RENAMEDSUCCESSFULLY....\n"); else printf("ERROR...!!!\n"); } else { close(p[0]); printf("ENTERAFILENAMETOBERENAMED\n"); scanf("%s",msg); write(p[1],msg,15); } } OUTPUT ls 2.ca.outfork.cmynewfile ENTERAFILENAMETOBERENAMED mynewfile FILENAMESENTBYCHILD:mynewfile ENTERANEWFILENAME myfile RENAMEDSUCCESSFULLY.... ls 2.ca.outfork.cmyfile 2

3..Implementaclientserverusingnamedpipes(FIFO).Theclientsendsafilenameto server.Theserversendsthecontentsofthefilebacktotheclientwhichprintsit. PROGRAM 3server.c #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<string.h> main() { intres1,res2,f1,f2,n; charbuf[100]; FILE*fin; unlink("/tmp/fifo1"); unlink("/tmp/fifo2"); res1=mkfifo("/tmp/fifo1",0666); if(res1==0) { printf("FIFO1CREATEDSUCCESSFULLY.\n"); } else { printf("FIFO1CREATIONFAILED.\n"); exit(1); } res2=mkfifo("/tmp/fifo2",0666); if(res2==0) { printf("FIFO2CREATEDSUCCESSFULLY.\n"); } else { printf("FIFO2CREATIONFAILED.\n"); exit(1); } f1=open("/tmp/fifo1",O_WRONLY); f2=open("/tmp/fifo2",O_RDONLY); if(f1<0||f2<0) { printf("PIPEOPENFAILED.\n"); exit(1); } if((n=read(f2,buf,100))==0) { 3

} buf[n]='\0'; fin=fopen(buf,"r"); if(fin!=NULL){ while(fscanf(fin,"%s",buf)!=EOF) { n=strlen(buf); write(f1,buf,n); bzero(buf,100); } printf("OPERATIONSUCCESSFULL\n"); } else{ printf("ERRORINOPENINGFILE.\n"); } close(f1); close(f2); } 3client.c #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<string.h> main() { intf1,f2,n; charbuf[100]; f1=open("/tmp/fifo1",O_RDONLY); f2=open("/tmp/fifo2",O_WRONLY); if((f1<0)||(f2<0)) { printf("PIPEOPENFAILED.\n"); exit(1); } printf("ENTERAFILENAME\n"); scanf("%s",buf); n=strlen(buf); write(f2,buf,n); bzero(buf,100); if(read(f1,buf,100)!=0){ printf("FILECONTENTSARE\n"); printf("%s\n",buf); bzero(buf,100); 4

printf("ERRORWHILEREADINGFILENAME.\n"); exit(1);

} else

printf("ERRORINOPENINGFILE\n"); close(f1); close(f2); unlink("/tmp/fifo1"); unlink("/tmp/fifo2"); } OUTPUT cc3server.co3server.out cc3client.co3client.out ./3server.out FIFO1CREATEDSUCCESSFULLY. FIFO2CREATEDSUCCESSFULLY. OPERATIONSUCCESSFULL ./3client.out ENTERAFILENAME abc FILECONTENTSARE hihellohwareyou

4.Implementtheaboveprogramusingpipesandfork(). PROGRAM #include<stdio.h> #include<stdlib.h> main() { intp[2],pid; charmsg[15],msg1[15]; pipe(p); pid=fork(); FILE*fin; if(pid>0){ close(p[1]); read(p[0],msg1,15); printf("FILENAMESENTBYCHILD:%s\n",msg1); fin=fopen(msg1,"r"); if(fin!=NULL){ while(fscanf(fin,"%s",msg1)!=EOF) { printf("%s\n",msg1); } } else{ printf("ERRORINOPENINGTHEFILE\n"); } } else { close(p[0]); printf("ENTERAFILENAMETOBEREAD\n"); scanf("%s",msg); write(p[1],msg,15); } } OUTPUT ./a.out ENTERAFILENAMETOBEREAD abc FILENAMESENTBYCHILD:abc hi hello hw are you

5.Implementaclientserverusingnamedpipes(FIFO).Theclientsendsafilenameto server.Theserversendsthecontentsofthefilebacktotheclientwhichprintsit. ModifytheaboveprogramtoimplementafilecopyprogramusingFIFO.Theclientsendsthe filenametoserver.Theserversendsthecontentstoclientandclientcopiesittoafile. PROGRAM 5serv.c #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<string.h> main() { intres1,res2,f1,f2,fd,n; charbuf[100]; FILE*fin; unlink("/tmp/fifo1"); unlink("/tmp/fifo2"); res1=mkfifo("/tmp/fifo1",0666); if(res1==0) { printf("FIFO1CREATEDSUCCESSFULLY.\n"); } else { printf("FIFO1CREATIONFAILED.\n"); exit(1); } res2=mkfifo("/tmp/fifo2",0666); if(res2==0) { printf("FIFO2CREATEDSUCCESSFULLY.\n"); } else { printf("FIFO2CREATIONFAILED.\n"); exit(1); } f1=open("/tmp/fifo1",O_WRONLY); f2=open("/tmp/fifo2",O_RDONLY); if(f1<0||f2<0) { printf("PIPEOPENFAILED.\n"); exit(1); } 7

if((n=read(f2,buf,100))==0) { printf("ERRORWHILEREADINGFILENAME.\n"); exit(1); } buf[n]='\0'; fin=fopen(buf,"r"); if(fin!=NULL){ while(fscanf(fin,"%s",buf)!=EOF) { n=strlen(buf); write(f1,buf,n); bzero(buf,100); } printf("OPERATIONSUCCESSFULL\n"); } else{ printf("ERRORINOPENINGFILE.\n"); } close(f1); close(f2); } 5clie.c #include<sys/types.h> #include<sys/stat.h> #include<stdio.h> #include<stdlib.h> #include<fcntl.h> #include<string.h> main() { intf1,f2,n; charbuf[100],msg[50]; FILE*fin; f1=open("/tmp/fifo1",O_RDONLY); f2=open("/tmp/fifo2",O_WRONLY); if((f1<0)||(f2<0)) { printf("PIPEOPENFAILED.\n"); exit(1); } printf("ENTERAFILENAME\n"); scanf("%s",buf); n=strlen(buf); write(f2,buf,n); printf("ENTERNEWFILENAME\n"); scanf("%s",msg); 8

if(read(f1,buf,100)!=0){ fin=fopen(msg,"w"); if(fin!=NULL){ fprintf(fin,"%s",buf); printf("CONTENTSCOPIEDSUCCESSFULLY\n"); } } else{ printf("ERRORINOPENINGFILE\n"); } close(f1); close(f2); unlink("/tmp/fifo1"); unlink("/tmp/fifo2"); } OUTPUT cc5serv.co5serv.out chindesktop:~/nparec$./a.out ENTERAFILENAMETOBEREAD abc FILENAMESENTBYCHILD:abc hi hello hw are you cc5clie.co5clie.out chindesktop:~/nparec$./5clie.out ENTERAFILENAME abc ENTERNEWFILENAME mynewabc CONTENTSCOPIEDSUCCESSFULLY

6.Writeaprogramtosendandreceivemessageusingsharedmemory. PROGRAM sndr_shm.c #include<sys/shm.h> #include<stdio.h> #include<sys/ipc.h> #include<sys/types.h> main() { intid; char*c; id=shmget((key_t)12,5,IPC_CREAT|0600); c=shmat(id,NULL,0); printf("ENTERAMESSAGETOBESENT\n"); scanf("%s",c); printf("MESSAGE%ssent\n",c); shmdt(c); } rcv.c #include<sys/shm.h> #include<sys/types.h> #include<sys/ipc.h> #include<stdio.h> main() { intid; char*c; id=shmget((key_t)12,0,0); c=shmat(id,NULL,0); printf("RECEIVEDMESSAGEIS%s\n",c); shmdt(c); shmctl(id,IPC_RMID,NULL); } OUTPUT: ./snd.out ENTERAMESSAGETOBESENT hello MESSAGEhellosent ./rcv.out RECEIVEDMESSAGEIShello

10

7.Writeaprogramtodisplaythesharedmemoryinformation. PROGRAM #include<sys/shm.h> #include<sys/types.h> #include<sys/ipc.h> #include<stdio.h> main() { intid; structshmid_dsst; id=shmget((key_t)12,0,0); shmctl(id,IPC_STAT,&st); printf("THECREATORUSERIDIS%d\n",st.shm_perm.cuid); printf("THECREATORGROUPIDIS%d\n",st.shm_perm.cgid); printf("THEOWNER'SUSERIDIS%d\n",st.shm_perm.uid); printf("THEOWNER'SGROUPIDIS%d\n",st.shm_perm.gid); printf("THEPERMISSIONSSETFORSHAREDMEMORY%d: %o\n",id,st.shm_perm.mode); printf("THESIZEOFTHESEGMENTINBYTESIS%d\n",st.shm_segsz); printf("PIDOFTHEPROCESSLASTOPERATEDIS:%d\n",st.shm_lpid); printf("THEPROCESSIDOFTHECREATORIS%d\n",st.shm_cpid); printf("NUMBEROFATTACHESIS%d\n",(int)st.shm_nattch); printf("LASTATTACHEDTIMEIS:%s\n",(char*)ctime(&st.shm_atime)); printf("LASTDETACHEDTIMEIS:%s\n",(char*)ctime(&st.shm_dtime)); printf("LASTCHANGEDTIMEIS:%s\n",(char*)ctime(&st.shm_ctime)); } OUTPUT: THECREATORUSERIDIS0 THECREATORGROUPIDIS0 THEOWNER'SUSERIDIS0 THEOWNER'SGROUPIDIS0 THEPERMISSIONSSETFORSHAREDMEMORY1:0 THESIZEOFTHESEGMENTINBYTESIS0 PIDOFTHEPROCESSLASTOPERATEDIS:1217310732 THEPROCESSIDOFTHECREATORIS134513484 NUMBEROFATTACHESIS134520820 LASTATTACHEDTIMEIS:ThuJan105:30:001970 LASTDETACHEDTIMEIS:MonMay2514:58:381931 LASTCHANGEDTIMEIS:SunApr704:23:401974

11

8.Writeaprogramtosendandreceivemessageusingmessagequeues. PROGRAM snd.c #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<stdio.h> #include<string.h> #include<stdlib.h> #definePERMS0666 main() { intqid,len,i; struct{ longmtype; charmtext[15]; }message; qid=msgget((key_t)6,IPC_CREAT|PERMS); if(qid==1){ printf("MSGGETFAILED\n"); exit(0); } printf("ENTERAMESSAGE\n"); scanf("%s",message.mtext); message.mtype=1; len=strlen(message.mtext); if(msgsnd(qid,&message,len,0)==1){ printf("MSGSNDFAILED\n"); exit(1); } } rcv.c #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<stdio.h> #include<string.h> #include<stdlib.h> #definePERMS0666 main() { intqid,len,i; struct{ longmtype; charmtext[15]; }message; 12

qid=msgget((key_t)6,IPC_CREAT|PERMS); if(qid==1){ printf("MSGGETFAILED\n"); exit(0); } message.mtype=2; bzero(message.mtext,15); //receivemessagefromsender //len=strlen(message.mtext); if(msgrcv(qid,&message,15,1,MSG_NOERROR)==1)

printf("MSGRCVFAILED.\n"); exit(1); } printf("MESSAGEIS%sANDITSMSGQUEUEIS%d\n",message.mtext,qid); } OUTPUT: ./snd.out ENTERAMESSAGE hello ./rcv.out MESSAGEIShelloANDITSMSGQUEUEIS0

13

9.CreateprogramstoimplementTCPclientandserver.Theclientandservershouldbeableto exchangemessages. PROGRAM tcps.c #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> main() { structsockaddr_inserv,cli; ints,n,s1; charstr[100],str1[100]; s=socket(AF_INET,SOCK_STREAM,0); serv.sin_family=AF_INET; serv.sin_port=htons(5000); serv.sin_addr.s_addr=inet_addr("127.0.0.1"); bind(s,(structsockaddr*)&serv,sizeof(serv)); listen(s,1); n=sizeof(cli); s1=accept(s,(structsockaddr*)&cli,&n); for(;;) { recv(s1,str1,sizeof(str1),0); if(strcmp(str1,"quit")==0) break; printf("MESSAGEFROMCLIENTIS%s\n",str1); printf("ENTERAMESSAGE\n"); scanf("%s",str); send(s1,str,sizeof(str),0); if(strcmp(str,"quit")==0) break; } close(s); close(s1); }

14

tcpc.c #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> main() { structsockaddr_inserv; ints; charstr[100],str1[100]; s=socket(AF_INET,SOCK_STREAM,0); serv.sin_family=AF_INET; serv.sin_port=htons(5000); serv.sin_addr.s_addr=inet_addr("127.0.0.1"); connect(s,(structsockaddr*)&serv,sizeof(serv)); for(;;) { printf("ENTERTHEMESSAGE:\n"); gets(str); send(s,str,sizeof(str),0); if(strcmp(str,"quit")==0) break; recv(s,str1,sizeof(str1),0); if(strcmp(str1,"quit")==0) break; printf("MESSAGEFROMSERVERIS:%s\n",str1); } close(s); }

15

OUTPUT cctcps.cotcps.out ./tcps.out MESSAGEFROMCLIENTISwelcome ENTERAMESSAGE world MESSAGEFROMCLIENTISof ENTERAMESSAGE LINUX MESSAGEFROMCLIENTISof ENTERAMESSAGE ^C cctcpc.cotcpc.out ./tcpc.out ENTERTHEMESSAGE: welcome MESSAGEFROMSERVERIS:world ENTERTHEMESSAGE: of MESSAGEFROMSERVERIS:LINUX ENTERTHEMESSAGE: ^C

16

10.ImplementaUDPclientandserver.Theclientshouldbeabletoexchangemessageswiththe server. PROGRAM udps.c #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<string.h> main(){ structsockaddr_incli; charstr1[100],str2[100]; ints,n; s=socket(AF_INET,SOCK_DGRAM,0); cli.sin_family=AF_INET; cli.sin_port=htons(5000); cli.sin_addr.s_addr=inet_addr("127.0.0.1"); bind(s,(structsockaddr*)&cli,sizeof(cli)); for(;;){ n=sizeof(cli); recvfrom(s,str2,sizeof(str2),0,(structsockaddr*)&cli,&n); if(strcmp(str2,"quit")==0) break; printf("MESSAGEFROMCLIENTIS%s\n",str2); printf("ENTERAMESSAGE\n"); scanf("%s",str1); sendto(s,str1,sizeof(str1),0,(structsockaddr*)&cli,n); if(strcmp(str1,"quit")==0) break; } }

17

udpc.c #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<string.h> main(){ structsockaddr_inserv; charstr1[100],str2[100]; ints,n; s=socket(AF_INET,SOCK_DGRAM,0); serv.sin_family=AF_INET; serv.sin_port=htons(5000); serv.sin_addr.s_addr=inet_addr("127.0.0.1"); for(;;){ printf("ENTERAMESSAGE\n"); scanf("%s",str1); sendto(s,str1,sizeof(str1),0,(structsockaddr*)&serv,sizeof(serv)); if(strcmp(str1,"quit")==0) break; recvfrom(s,str2,sizeof(str2),0,(structsockaddr*)&serv,&n); if(strcmp(str2,"quit")==0) break; printf("MESSAGEFROMSERVERIS%s\n",str2); } } OUTPUT ccudps.coudps.out ./udps.out MESSAGEFROMCLIENTIShello ENTERAMESSAGE welcome ccudpc.coudpc.out ./udpc.out ENTERAMESSAGE hello MESSAGEFROMSERVERISwelcome ENTERAMESSAGE

18

11.ImplementasimpleDNSclientandserverusingUDPSocketprogramming. PROGRAM dnsserver.c #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<stdio.h> #include<strings.h> #include<string.h> struct{ charname[50]; charip[30]; }dns; main() { ints,n,f=0; FILE*fp; charname[30],ip[30]; s=socket(AF_INET,SOCK_DGRAM,0); structsockaddr_inser,cli; ser.sin_family=AF_INET; ser.sin_port=htons(5000); ser.sin_addr.s_addr=inet_addr("127.0.0.1"); bind(s,(structsockaddr*)&ser,sizeof(ser)); n=sizeof(cli); while(1) { bzero(name,30); recvfrom(s,name,20,0,(structsockaddr*)&cli,&n); if(strcmp(name,"quit")==0) { printf("QUITTING..........\n"); break; } fp=fopen("dns.txt","r"); f=0; while(fread(&dns,1,sizeof(dns),fp)!=0) { if(strcmp(dns.name,name)==0) { strcpy(ip,dns.ip); f=1; break; } } close(fp); if(f==0) 19

{ printf("INFORMATIONNOTAVAILABLE\n"); strcpy(ip,"NOTAVAILABLE\n"); } else printf("INFORMATIONSENTSUCCESSFULLY\n"); sendto(s,ip,20,0,(structsockaddr*)&cli,n); } }

dnsclient.c #include<stdio.h> #include<string.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> main() { ints,n; charname[30],ip[30]; s=socket(AF_INET,SOCK_DGRAM,0); structsockaddr_inser; ser.sin_family=AF_INET; ser.sin_port=htons(5000); ser.sin_addr.s_addr=inet_addr("127.0.0.1"); while(1) { printf("ENTERNAME:[ENTERquitTOCANCEL]\n"); scanf("%s",name); sendto(s,name,strlen(name),0,(structsockaddr*)&ser,sizeof(ser)); n=sizeof(ser); if(strcmp(name,"quit")==0) break; recvfrom(s,ip,20,0,(structsockaddr*)&ser,&n); printf("IPADDRESSIS:%s\n",ip); } } vidns.c #include<stdio.h> #include<fcntl.h> struct{ charname[50]; charip[30]; }dns; main() { 20

FILE*fp; charc[2]; fp=fopen("dns.txt","w+"); do { printf("ENTERNAME:\n"); scanf("%s",dns.name); printf("ENTERIP:\n"); scanf("%s",dns.ip); fwrite(&dns,1,sizeof(dns),fp); printf("DOYOUWANTTOCONTINUE???:\n"); scanf("%s",c); }while(strcmp(c,"y")==0); fclose(fp); printf("FILECREATED.\n"); } OUTPUT ccdns.codns.out ./dns.out ENTERNAME: chintech ENTERIP: 192.168.1.8 DOYOUWANTTOCONTINUE???: n FILECREATED. ./dnss.out INFORMATIONSENTSUCCESSFULLY ./dnsc.out ENTERNAME:[ENTERquitTOCANCEL] chintech IPADDRESSIS:192.168.1.8 google IPADDRESSIS:NOTAVAILABLE ENTERNAME:[ENTERquitTOCANCEL] quit

21

12.ImplementasimpleFTPclientandserver. PROGRAM ftps.c #include<stdio.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<fcntl.h> intmain(intargc,char**argv) { ints,c,n; charb1[20],b2[10]="ERROR.."; charb3[30]; FILE*fp; structsockaddr_inser,cli; s=socket(AF_INET,SOCK_STREAM,0); ser.sin_family=AF_INET; ser.sin_port=5000; ser.sin_addr.s_addr=inet_addr("127.0.0.1"); bind(s,(structsockaddr*)&ser,sizeof(ser)); listen(s,1); n=sizeof(cli); c=accept(s,(structsockaddr*)&cli,&n); bzero(b1,20); recv(c,b1,sizeof(b1),0); printf("THEFILENAMEIS:%s\n",b1); fp=fopen(b1,"r"); if(fp==NULL) { printf("NOSUCHFILE...\n"); send(c,b2,sizeof(b2),0); close(c); close(s); exit(0); } while(fscanf(fp,"%s",b3)!=EOF) { send(c,b3,10,0); bzero(b3,30); } printf("CONTENTSTRANSFERREDSUCCESSFULLY....\n"); close(c); close(s); fclose(fp); }

22

ftpc.c #include<stdio.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<fcntl.h> #include<string.h> main() { ints,v; FILE*fp; charb1[20],b2[10],b3[30]; structsockaddr_inser; s=socket(AF_INET,SOCK_STREAM,0); ser.sin_family=AF_INET; ser.sin_port=5000; ser.sin_addr.s_addr=inet_addr("127.0.0.1"); printf("ENTERAFILENAME:"); scanf("%s",b1); printf("\n"); connect(s,(structsockaddr*)&ser,sizeof(ser)); b1[strlen(b1)]='\0'; send(s,b1,strlen(b1),0); fp=fopen(b1,"w+"); printf("CONTENTSARE:\n"); do {v=recv(s,b3,10,0); printf("%s\n",b3); fprintf(fp,"%s",b3); bzero(b3,30); }while(v!=0); close(fp); close(s); }

23

OUTPUT ./ftpc.out ENTERAFILENAME:samp CONTENTSARE: heloo hw r u hope u r fine ./ftps.out THEFILENAMEIS:samp CONTENTSTRANSFERREDSUCCESSFULLY....

24

SYSTEMSPROGRAMMING AND COMPILERDESIGNPROGRAMS

25

8086MICROPROCESSOR
Intel8086microprocessorisafirstmemberofx86familyofprocessors.Advertisedasa"source code compatible" with Intel 8080 and Intel 8085 processors, the 8086 was not object code compatiblewiththem.The8086hascomplete16bitarchitecture16bitinternalregisters,16bit databus,and20bitaddressbus(1MBofphysicalmemory).Becausetheprocessorhas16bit indexregistersandmemorypointers,itcaneffectivelyaddressonly64KBofmemory.Toaddress memorybeyond64KBtheCPUusessegmentregisterstheseregistersspecifymemorylocations forcode,stack,dataandextradata64KBsegments.Thesegmentscanbepositionedanywherein memory,and,ifnecessary,userprogramscanchangetheirposition.Thisaddressingmethodhas onebigadvantageitisveryeasytowritememoryindependentcodewhenthesizeofcode,stack anddataissmallerthan64KBeach.Thecomplexityofthecodeandprogrammingincreases, sometimessignificantly,whenthesizeofstack,dataand/codeislargerthan64KB.Tosupport differentvariationsofthisawkwardmemoryaddressingschememany8086compilersincluded6 differentmemorymodels:tiny,small,compact,medium,largeandhuge.64KBdirectaddressing limitation was eliminated with the introduction of the 32bit protected mode in Intel 80386 processor.

Memory
Program,dataandstackmemoriesoccupythesamememoryspace.Thetotaladdressablememory sizeis1MBKB.Asthemostoftheprocessorinstructionsuse16bitpointerstheprocessorcan effectivelyaddressonly64KBofmemory.Toaccessmemoryoutsideof64KBtheCPUuses specialsegmentregisterstospecifywherethecode,stackanddata64KBsegmentsarepositioned within1MBofmemory. Programmemoryprogramcanbelocatedanywhereinmemory.Jumpandcallinstructionscan beusedforshortjumpswithincurrentlyselected64KBcodesegment,aswellasforfarjumps anywherewithin1MBofmemory.Allconditionaljumpinstructionscanbeusedtojumpwithin approximately+127127bytesfromcurrentinstruction. Datamemorythe8086processorcanaccessdatainanyoneoutof4availablesegments,which limitsthesizeofaccessiblememoryto256KB(ifallfoursegmentspointtodifferent64KB blocks).AccessingdatafromtheData,Code,StackorExtrasegmentscanbeusuallydoneby prefixinginstructionswiththeDS:,CS:,SS:orES:(someregistersandinstructionsbydefault mayusetheESorSSsegmentsinsteadofDSsegment). Word data can be located at odd or even byte boundaries. The processor uses two memory accessestoread16bitwordlocatedatoddbyteboundaries.Readingworddatafromevenbyte boundariesrequiresonlyonememoryaccess. Stackmemory canbeplacedanywhereinmemory.Thestackcanbelocatedatoddmemory addresses,butitisnotrecommendedforperformancereasons

26

Interrupts
Theprocessorhasthefollowinginterrupts: INTR isamaskablehardwareinterrupt.Theinterruptcanbeenabled/disabledusingSTI/CLI instructionsorusingmorecomplicatedmethodofupdatingtheFLAGSregisterwiththehelpof thePOPFinstruction.Whenaninterruptoccurs,theprocessorstoresFLAGSregisterintostack, disablesfurtherinterrupts,fetchesfromthebusonebyterepresentinginterrupttype,andjumpsto interruptprocessingroutineaddressofwhichisstoredinlocation4*<interrupttype>.Interrupt processingroutineshouldreturnwiththeIRETinstruction. NMIisanonmaskableinterrupt.InterruptisprocessedinthesamewayastheINTRinterrupt. InterrupttypeoftheNMIis2,i.e.theaddressoftheNMIprocessingroutineisstoredinlocation 0008h.Thisinterrupthashigherprioritythenthemaskableinterrupt. Softwareinterruptscanbecausedby: INTinstructionbreakpointinterrupt.Thisisatype3interrupt. INT<interruptnumber>instructionanyoneinterruptfromavailable256interrupts. INTOinstructioninterruptonoverflow SinglestepinterruptgeneratediftheTFflagisset.Thisisatype1interrupt.Whenthe CPU processes this interrupt it clears TF flag before calling the interrupt processing routine. Processorexceptions:divideerror(type0),unusedopcode(type6)andescapeopcode (type7). Softwareinterruptprocessingisthesameasforthehardwareinterrupts.

Registers
Mostoftheregisterscontaindata/instructionoffsetswithin64KBmemorysegment.Thereare fourdifferent64KBsegmentsforinstructions,stack,dataandextradata.Tospecifywherein1 MBofprocessormemorythese4segmentsarelocatedthe8086microprocessorusesfoursegment registers: Codesegment (CS)isa16bitregistercontainingaddressof64KBsegmentwithprocessor instructions. The processor uses CS segment for all accesses to instructions referenced by instruction pointer (IP) register. CS register cannot be changed directly. The CS register is automaticallyupdatedduringfarjump,farcallandfarreturninstructions. Stacksegment(SS)isa16bitregistercontainingaddressof64KBsegmentwithprogramstack. Bydefault,theprocessorassumesthatalldatareferencedbythestackpointer(SP)andbase pointer(BP)registersislocatedinthestacksegment.SSregistercanbechangeddirectlyusing POPinstruction. Datasegment(DS)isa16bitregistercontainingaddressof64KBsegmentwithprogramdata. Bydefault,theprocessorassumesthatalldatareferencedbygeneralregisters(AX,BX,CX,DX) andindexregister(SI,DI)islocatedinthedatasegment.DSregistercanbechangeddirectly usingPOPandLDSinstructions. 27

Extra segment (ES) is a 16bit register containing address of 64KB segment, usually with programdata.Bydefault,theprocessorassumesthattheDIregisterreferencestheESsegmentin string manipulation instructions. ES register can be changed directly using POP and LES instructions. It is possible to change default segments used by general and index registers by prefixing instructionswithaCS,SS,DSorESprefix. Allgeneralregistersofthe8086microprocessorcanbeusedforarithmeticandlogicoperations. Thegeneralregistersare: Accumulatorregisterconsistsof28bitregistersALandAH,whichcanbecombinedtogether andusedasa16bitregisterAX.ALinthiscasecontainstheloworderbyteoftheword,andAH containsthehighorderbyte.AccumulatorcanbeusedforI/Ooperationsandstringmanipulation. Baseregisterconsistsof28bitregistersBLandBH,whichcanbecombinedtogetherandusedas a16bitregisterBX.BLinthiscasecontainstheloworderbyteoftheword,andBHcontainsthe highorderbyte.BX registerusuallycontains adatapointerusedforbased,basedindexedor registerindirectaddressing. Countregisterconsistsof28bitregistersCLandCH,whichcanbecombinedtogetherandused asa16bitregisterCX.Whencombined,CLregistercontainstheloworderbyteoftheword,and CHcontainsthehighorderbyte.Countregistercanbeusedasacounterinstringmanipulation andshift/rotateinstructions. Dataregisterconsistsof28bitregistersDLandDH,whichcanbecombinedtogetherandusedas a16bitregisterDX.Whencombined,DLregistercontainstheloworderbyteoftheword,and DHcontainsthehighorderbyte.DataregistercanbeusedasaportnumberinI/Ooperations.In integer32bitmultiplyanddivideinstructiontheDXregistercontainshighorderwordofthe initialorresultingnumber. Thefollowingregistersarebothgeneralandindexregisters: StackPointer(SP)isa16bitregisterpointingtoprogramstack. BasePointer(BP)isa16bitregisterpointingtodatainstacksegment.BPregisterisusuallyused forbased,basedindexedorregisterindirectaddressing. SourceIndex(SI)isa16bitregister.SIisusedforindexed,basedindexedandregisterindirect addressing,aswellasasourcedataaddressinstringmanipulationinstructions. DestinationIndex (DI)isa16bitregister.DIisusedforindexed,basedindexedandregister indirectaddressing,aswellasadestinationdataaddressinstringmanipulationinstructions. Otherregisters: InstructionPointer(IP)isa16bitregister. Flagsisa16bitregistercontaining91bitflags: OverflowFlag(OF)setiftheresultistoolargepositivenumber,oristoosmallnegative numbertofitintodestinationoperand. DirectionFlag(DF)ifsetthenstringmanipulationinstructionswillautodecrementindex registers.Ifclearedthentheindexregisterswillbeautoincremented. 28

InterruptenableFlag(IF)settingthisbitenablesmaskableinterrupts. SinglestepFlag(TF)ifsetthensinglestepinterruptwilloccurafterthenextinstruction. SignFlag(SF)setifthemostsignificantbitoftheresultisset. ZeroFlag(ZF)setiftheresultiszero. AuxiliarycarryFlag(AF)setiftherewasacarryfromorborrowtobits03intheAL register. ParityFlag(PF)setifparity(thenumberof"1"bits)intheloworderbyteoftheresultis even. CarryFlag(CF)setiftherewasacarryfromorborrowtothemostsignificantbitduring lastresultcalculation.

Addressingmodes
Impliedthedatavalue/dataaddressisimplicitlyassociatedwiththeinstruction. Registerreferencesthedatainaregisterorinaregisterpair. Immediatethedataisprovidedintheinstruction. Directtheinstructionoperandspecifiesthememoryaddresswheredataislocated. Registerindirect instructionspecifiesaregistercontaininganaddress,wheredataislocated. ThisaddressingmodeworkswithSI,DI,BXandBPregisters. Based8bitor16bitinstructionoperandisaddedtothecontentsofabaseregister(BXorBP), theresultingvalueisapointertolocationwheredataresides. Indexed8bitor16bitinstructionoperandisaddedtothecontentsofanindexregister(SIor DI),theresultingvalueisapointertolocationwheredataresides. BasedIndexedthecontentsofabaseregister(BXorBP)isaddedtothecontentsofanindex register(SIorDI),theresultingvalueisapointertolocationwheredataresides. BasedIndexedwithdisplacement8bitor16bitinstructionoperandisaddedtothecontentsof abaseregister(BXorBP)andindexregister(SIorDI),theresultingvalueisapointertolocation wheredataresides.

InstructionSet
InstructionsetofIntel8086processorconsistsofthefollowinginstructions: Datamovinginstructions Thedatatransferinstructionsmovedatabetweenmemoryandthegeneralpurposeandsegment registers.Theyalsoperformspecificoperationssuchasconditionalmoves,stackaccess,and dataconversion.

29

MOVMovedatabetweengeneralpurposeregisters;movedatabetween memoryandgeneralpurposeorsegmentregisters;moveimmediates togeneralpurposeregisters CMOVE/CMOVZConditionalmoveifequal/Conditionalmoveifzero CMOVNE/CMOVNZConditionalmoveifnotequal/Conditionalmoveifnotzero CMOVA/CMOVNBEConditionalmoveifabove/Conditionalmoveifnotbelow orequal CMOVAE/CMOVNBConditionalmoveifaboveorequal/Conditionalmoveif notbelow ArithmeticInstructions ADDIntegeradd ADCAddwithcarry SUBSubtract SBBSubtractwithborrow IMULSignedmultiply MULUnsignedmultiply IDIVSigneddivide DecimalArithmetic Thedecimalarithmeticinstructionsperformdecimalarithmeticonbinarycodeddecimal(BCD) data. DAADecimaladjustafteraddition DASDecimaladjustaftersubtraction AAAASCIIadjustafteraddition AASASCIIadjustaftersubtraction AAMASCIIadjustaftermultiplication AADASCIIadjustbeforedivision LogicalInstructions ThelogicalinstructionsperformbasicAND,OR,XOR,andNOTlogicaloperationsonbyte, word,anddoublewordvalues.

30

ANDPerformbitwiselogicalAND ORPerformbitwiselogicalOR XORPerformbitwiselogicalexclusiveOR NOTPerformbitwiselogicalNOT ShiftandRotateInstructions Theshiftandrotateinstructionsshiftandrotatethebitsinwordanddoublewordoperands SARShiftarithmeticright SHRShiftlogicalright SAL/SHLShiftarithmeticleft/Shiftlogicalleft ControlTransferInstructions Thecontroltransferinstructionsprovidejump,conditionaljump,loop,andcallandreturnoper ationstocontrolprogramflow. JMPJump JE/JZJumpifequal/Jumpifzero JNE/JNZJumpifnotequal/Jumpifnotzero JA/JNBEJumpifabove/Jumpifnotbeloworequal JAE/JNBJumpifaboveorequal/Jumpifnotbelow JB/JNAEJumpifbelow/Jumpifnotaboveorequal StringInstructions Thestringinstructionsoperateonstringsofbytes,allowingthemtobemovedtoandfrom memory. MOVS/MOVSBMovestring/Movebytestring MOVS/MOVSWMovestring/Movewordstring MOVS/MOVSDMovestring/Movedoublewordstring CMPS/CMPSBComparestring/Comparebytestring CMPS/CMPSWComparestring/Comparewordstring FlagControlInstructions TheflagcontrolinstructionsoperateontheflagsintheEFLAGSregister.

31

STCSetcarryflag CLCClearthecarryflag CMCComplementthecarryflag CLDClearthedirectionflag STDSetdirectionflag LAHFLoadflagsintoAHregister SAHFStoreAHregisterintoflags SegmentRegisterInstructions Thesegmentregisterinstructionsallowfarpointers(segmentaddresses)tobeloadedintothe segmentregisters. LDSLoadfarpointerusingDS LESLoadfarpointerusingES LFSLoadfarpointerusingFS LGSLoadfarpointerusingGS LSSLoadfarpointerusingSS

32

1.Programtodisplayacharacteronthescreen. ALGORITHM Step1:Start Step2:DisplayacharacterusingDOS02hfunction Step3:Endingtheprogramwith4ch Step4:End PROGRAM .modelsmall .stack .code movdl,'A' movah,02h int21h movah,4ch int21h

end

OUTPUT A

33

2.Programreadacharacterfromthekeyboardanddisplayitonthescreen. ALGORITHM Step1:Start Step2:EnteracharacterusingDOS01hfunction Step3:DisplayacharacterusingDOS02hfunction Step4:Stop PROGRAM .modelsmall .data msg1db13,10,"**********************$" msg2db13,10,"ENTERACHAR:$" msg3db13,10,"ENTEREDCHARIS:$" .code movax,@data movds,ax movdx,offsetmsg1 movah,09h int21h movdx,offsetmsg2 movah,09h int21h movah,01h int21h movbl,al movdx,offsetmsg3 movah,09h int21h movdl,bl movah,02h int21h movdx,offsetmsg1 movah,09h int21h movah,4ch int21h

end

OUTPUT ************************ ENTERACHAR:b ENTEREDCHARIS:b 34

3.Programtodisplayastringonthescreen. ALGORITHM Step1:Start Step2:DisplayastringusingDOS09hfunction Step3:Stop PROGRAM .modelsmall .stack .data totaldb"******$" .code movax,@data movds,ax movdx,offsettotal movah,09h int21h movah,4ch int21h end OUTPUT ******

35

4.Program to display a string on the screen using DOS call function 02h. ALGORITHM Step1:Start Step2:DisplaycharacterwithDOS02hfunction Step3:Repeatstep2untilendofline Step4:Stop PROGRAM .modelsmall .stack .data msg2db10,13,"STRINGIS:$" sdb13,10,"SPCDPROGRAMMING$" .code movax,@data movds,ax movdx,offsetmsg2 movah,09h int21h movsi,offsets rpt: movah,02h movdl,[si] int21h incsi movbh,[si] cmpbh,'$' jnzrpt

end

movah,4ch int21h

OUTPUT STRINGIS: SPCDPROGRAMMING

36

5.ProgramtoreadastringfromkeyboardanddisplyitonthescreenusingDOScallfunction02h. ALGORITHM Step1:Start Step2:Readastringfromkeyboardusing01hfunction Step3:DisplaycharacterusingDOS02hfunction Step4:Repeatstep3untilendofline Step5:Stop PROGRAM .modelsmall .stack .data msg1db10,13,"ENTERASTRING:$" msg2db10,13,"ENTEREDSTRINGIS:$" sdb20dup(?) .code movax,@data movds,ax movah,09h movdx,offsetmsg1 int21h movsi,offsets rpt1: movah,01h int21h mov[si],al incsi cmpal,'$' jnzrpt1 movah,09h movdx,offsetmsg2 int21h movsi,offsets rpt2: movdl,[si] cmpdl,'$' jzrpt3 movah,02h int21h incsi jmprpt2 rpt3: movah,4ch int21h end OUTPUT ENTERASTRING:SPCD$ ENTEREDSTRINGIS:SPCD 37

6.ProgramtoreadastringfromkeyboardanddisplayitonthescreenusingDOScallfunction09h ALGORITHM Step1:Start Step2:Readastringfromkeyboardusing01hfunction Step3:Displaycharacterusing09hfunction Step4:Repeatstep3untilendofline Step5:Stop PROGRAM .modelsmall .stack .data msg1db10,13,"ENTERASTRING$" msg2db10,13,"ENTEREDSTRINGIS:$" sdb20dup(?) .code movax,@data movds,ax movah,09h movdx,offsetmsg1 int21h movsi,offsets rpt1: movah,01h int21h mov[si],al movbh,[si] incsi cmpbh,'$' jnzrpt1 movah,09h movdx,offsetmsg2 int21h movah,09h movdx,offsets int21h movah,4ch int21h end OUTPUT ENTERASTRING:HELLO$ ENTEREDSTRINGIS:HELLO

38

8.ProgramtoreaddatafromkeyboardusingBIOSfunction00h ALGORITHM Step1:Start Step2:ReadastringfromkeyboardusingBIOS00hfunction Step3:DisplaycharacterusingDOS09hfunction Step4:Repeatstep3untilendofline Step5:Stop PROGRAM .modelsmall .stack .data msg1db10,13,"ENTERASTRING$" msg2db10,13,"ENTEREDSTRINGIS:$" sdb20dup(?) .code movax,@data movds,ax movah,09h movdx,offsetmsg1 int21h movsi,offsets rpt1: movah,00h int16h mov[si],al movbh,[si] incsi cmpbh,'$' jnzrpt1 movah,09h movdx,offsetmsg2 int21h movah,09h movdx,offsets int21h movah,4ch int21h end OUTPUT ENTERASTRING: ENTEREDSTRINGIS:WELCOME

39

9.Program to display a string on the screen implement using macros. ALGORITHM Step1:Start Step2:DisplayastringusingDOS09hfunction Step-3: Stop PROGRAM .model small .stack disp macro msg mov dx,offset msg mov ah,09h int 21h endm .data str db "HELLOWORLD$" .code mov ax,@data mov ds,ax disp str mov ah,4ch int 21h end OUTPUT HELLOWORLD

40

10.Program to read a string from keyboard using DOS call function 01h and display it using 02h, implement using macros. ALGORITHM Step1:Start Step2:ReadastringfromkeyboardusingDOS01hfunction Step3:DisplaycharacterusingDOS02hfunction Step-4: Repeat step-2 until end of line Step-5: Stop PROGRAM .modelsmall .stack readmacros1 movsi,offsets1 rpt1: movah,01h int21h mov[si],al incsi cmpal,'$' jnzrpt1 endm dispmacros2 movsi,offsets2 rpt2: movdl,[si] cmpdl,'$' jzrpt3 movah,02h int21h incsi jmprpt2 rpt3: endm .data msg1db10,13,"ENTERASTRING$" msg2db10,13,"ENTEREDSTRINGIS:$" strdb20dup(?) .code movax,@data movds,ax movah,09h movdx,offsetmsg1 int21h readstr movah,09h movdx,offsetmsg2 int21h 41

dispstr movah,4ch int21h end OUTPUT ENTERASTRING:SOFTWARE$ ENTEREDSTRINGIS:SOFTWARE

42

11.Program to check whether the number is palindrome or not. ALGORITHM Step-1: Start Step-2: Read a number using DOS 01h function and store in a stack Step-3: Reverse the number and store in a stack Step-4: Compare each digit Step-5: if all digits are equal print number is palindrome Otherwise print number is not palindrome using DOS 09h function Step-6: Stop PROGRAM .model small .stack disp macro m lea dx,m mov ah,09h int 21h endm .data msg1 db 13,10,"ENTER A NO:$" msg2 db 13,10,"ENTERED NO IS :$" msg3 db 13,10,"GIVEN NO IS PALINDROME:$" msg4 db 13,10,"GIVEN NO IS NOT PALINDROME:$" a db 10 dup(0) b db 10 dup(0) .code mov ax,@data mov ds,ax mov si,offset a mov bh,00 disp msg1 rpt1: mov ah,01h int 21h mov[si],al inc si inc bh cmp al,13 jnz rpt1 dec si mov di,offset b dec bh mov cl,bh dec si rpt2: mov dl,[si] mov[di],dl 43

inc di dec si dec bh jnz rpt2 mov dl,'$' mov [di],dl disp msg2 disp b mov si,offset a mov di,offset b rpt4: mov al,[si] mov dl,[di] cmp al,dl jnz rpt3 inc si inc di dec cl jnz rpt4 disp msg3 jmp rpt5 rpt3: disp msg4 rpt5: mov ah,4ch int 21h end OUTPUT ENTER A NO:121 ENTERED NO IS :121 GIVEN NO IS PALINDROME: ENTER A NO:122 ENTERED NO IS :122 GIVEN NO IS NOT PALINDROME:

44

12.Program to check whether the number is odd or even. ALGORITHM Step-1: Start Step-2: Read the number using DOS 01h function Step-3: Divide number by 2 Step-4: If Remainder is 0 print number is even Otherwise print number is odd using DOS 09h function Step-5: Stop PROGRAM .modelsmall .data msg1db10,13,"ENTERTWODIGITNUMBER$" msg2db10,13,"GIVENNUMBERISEVEN$" msg3db10,13,"GIVENNUMBERISODD$" numdb0 .code movax,@data movds,ax movah,09h movdx,offsetmsg1 int21h ;readanumber movah,01h int21h subal,30 movbl,0ah moval,bl movnum,al movah,01h int21h subal,30 addnum,al ;DIVISION moval,num movah,00h movbl,02h divbl cmpah,00 jerpt1 movah,09h movdx,offsetmsg3 int21h jmpskip rpt1:movah,09h movdx,offsetmsg2 45

int21h skip: movah,4ch int21h end OUTPUT ENTERTWODIGITNUMBER22 GIVENNUMBERISEVEN ENTERTWODIGITNUMBER23 GIVENNUMBERISODD

46

12.Program to find sum of n numbers. ALGORITHM Step-1: Start Step-2: Read the limit using DOS 01h function Step-3: Read the numbers using DOS 01h function Step-4: Calculate the sum of the given numbers Step-5: Print the sum using using DOS 09h function Step-6: Stop PROGRAM .model small .stack print macro msg mov ah,09h lea dx,msg int 21h endm read macro num mov ah,01h int 21h sub al,'0' mov bl,0ah mul bl mov num,al mov ah,01h int 21h sub al,'0' add num,al endm .data num db ? temp db ? ntable db 10 dup(?) result db 10 dup (0) msg3 db 10,13,"SUM IS:$" msg1 db 10,13,"ENTER THE LIMIT(2 DIGIT):$" msg2 db 10,13,"ENTER THE NUMBER(2 DIGIT):$" .code mov ax,@data mov ds,ax print msg1 read num lea si,ntable mov cl,num nextread: print msg2 read temp 47

mov al,temp mov [si],al inc si loop nextread mov si,offset ntable mov ah,00 mov al,[si] mov cl,01 nextchk: inc si cmp cl,num je nomore mov bh,00 mov bl,[si] add ax,bx inc cl jmp nextchk nomore: mov si,offset result call hexasc print msg3 print result mov ah,4ch int 21h hexasc proc near push ax push bx push cx push dx push si mov cx,00h mov bx,0ah rpt2:mov dx,00h div bx add dl,'0' inc cx push dx cmp ax,0ah jge rpt2 add al,'0' mov [si],al rpt3: pop ax inc si mov [si],al loop rpt3 inc si mov al,'$' mov [si],al pop si pop dx pop cx pop bx 48

pop ax ret hexasc endp end OUTPUT ENTER THE LIMIT(2 DIGIT): 03 ENTER THE NUMBER(2 DIGIT):01 ENTER THE NUMBER(2 DIGIT):02 ENTER THE NUMBER(2 DIGIT):03 SUM IS:06

49

13.Program to find largest of N numbers. ALGORITHM Step-1: Start Step-2: Read the limit using DOS 01h function Step-3: Read a numbers using DOS 01h function Step-4: Compare each number Step-5: Find the largest number Step-6: Print the largest number using DOS 01h function Step-7: Stop PROGRAM .model small .stack print macro msg mov ah,09h lea dx,msg int 21h endm read macro num mov ah,01h int 21h sub al,'0' mov bl,0ah mul bl mov num,al mov ah,01h int 21h sub al,'0' add num,al endm .data num db ? temp db ? larg db ? ntable db 10 dup(?) msg3 db 10,13,"LARGEST IS:$" msg1 db 10,13,"ENTER THE LIMIT:$" msg2 db 10,13,"ENTER A NUMBER:$" .code mov ax,@data mov ds,ax print msg1 read num lea si,ntable mov cl,num nextread: print msg2 read temp mov al,temp 50

mov [si],al inc si loop nextread mov si,offset ntable mov bl,[si] mov cl,01 nextchk: inc si cmp cl,num je nomore cmp bl,[si] jge skip mov bl,[si] skip:inc cl jmp nextchk nomore: mov ah,00 mov al,bl mov si,offset larg call hexasc print msg3 print larg mov ah,4ch int 21h hexasc proc near push ax push bx push cx push dx push si mov cx,00h mov bx,0ah rpt2:mov dx,00h div bx add dl,'0' inc cx push dx cmp ax,0ah jge rpt2 add al,'0' mov [si],al rpt3: pop ax inc si mov [si],al loop rpt3 inc si mov al,'$' mov [si],al pop si pop dx pop cx pop bx 51

pop ax ret hexasc endp end OUTPUT ENTER THE LIMIT:03 ENTER A NUMBER:05 ENTER A NUMBER:11 ENTER A NUMBER:01 LARGEST IS: 11

52

14.Implement an application using ALP to reverse an entered string. ALGORITHM Step-1:Read a string1 using DOS 01h function Step-2:Read character by character from read string1 and store in another string2 Step-3: Display string2 using DOS 01h function Step-4:Stop PROGRAM .model small .stack disp macro m lea dx,m mov ah,09h int 21h endm .data msg1 db 13,10,"ENTER A STRING:$" msg2 db 13,10,"REVERSED STRING IS :$" a db 10 dup(0) b db 10 dup(0) .code mov ax,@data mov ds,ax mov si,offset a mov bh,00 disp msg1 rpt1: mov ah,01h int 21h mov[si],al inc si inc bh cmp al,13 jnz rpt1 dec si mov di,offset b dec bh mov cl,bh dec si rpt2: mov dl,[si] mov[di],dl inc di dec si dec bh jnz rpt2 mov dl,'$' mov [di],dl 53

disp msg2 disp b mov ah,4ch int 21h end OUTPUT ENTER A STRING:qwerty REVERSED STRING IS:ytrewq

54

15.Write an ALP to perform linear search on an array. ALGORITHM Step-1:Read n numbers Step-2:Read number to be searched using DOS 01h function Step-3:Compare number to be searched with all the numbers Step-4:If found then display position and goto step-6 Step-5:Display NUMBER NOT FOUND using DOS 01h function Step-6:Stop PROGRAM .model small .stack disp macro msg mov dx,offset msg mov ah,09h int 21h endm .data msg1 db 13,10,"ENTER A LIMIT:$" msg2 db 13,10,"ENTER NUMBER :$" msg3 db 13,10,"NUMBERS ARE :$" msg4 db 13,10,"ENTER NUMBER TO BE SEARCHED:$" msg5 db 13,10,"NUMBER FOUND AT:$" msg6 db 13,10,"NUMBER NOT FOUND$" str1 db 10 dup(0) num db 0 newnum db 0 .code mov ax,@data mov ds,ax ;read limit disp msg1 mov ah,01h int 21h sub al,'0' mov num,al ;read elements mov cl,num mov si,offset str1 rpt1: disp msg2 mov ah,01h int 21h mov[si],al inc si loop rpt1 mov dl,'$' mov [si],dl ;display string 55

disp msg3 disp str1 ;read a num disp msg4 mov ah,01h int 21h mov newnum,al ;search mov cl,0 mov si,offset str1 rpt2: mov dl,[si] inc si cmp dl,'$' jz rpt3 inc cl cmp newnum,dl jnz rpt2 rpt3: cmp cl,num jg rpt4 disp msg5 add cl,'0' mov dl,cl mov ah,02h int 21h jmp rpt5 rpt4: disp msg6 ;end rpt5: mov ah,4ch int 21h end OUTPUT ENTER A LIMIT : 4 ENTER NUMBER:5 ENTER NUMBER:8 ENTER NUMBER:6 ENTER NUMBER:3 NUMBERS ARE : 5863 ENTER NUMBER TO BE SEARCHED:8 NUMBER FOUND AT:2

56

16. Write an ALP to sort on an array. ALGORITHM Step-1: Start Step-2: Read the numbers using DOS 01h function Step-3: Compare each number with the next number Step-4: Display the sorted list using DOS 01h function Step-5: Stop PROGRAM display macro str mov dx,offset str mov ah,09h int 21h endm .model small .stack .data str1 db 10,13,"ENTER THE NUMBERS str2 db 10,13,"ENTERED NUMBERS str3 db 10,13,"AFTER SORTING : num db 20 dup(?) sort db 20 dup(?) .code mov ax,@data mov ds,ax display str1 mov si,offset num rpt1:mov ah,01h int 21h mov [si],al inc si cmp al,'$' jnz rpt1 display str2 display num display str3 mov si,offset num mov di,offset num rpt2: mov al,[si] cmp al,'$' jz final rpt3:mov al,[si] inc di mov bl,[di] cmp bl,'$' jz last cmp bl,al 57

: : $"

$" $"

jbe swap jmp rpt2 swap:mov cl,[di] mov [di],al mov [si],cl cmp bl,'$' jnz rpt3 ;swapping last:inc si mov di,si jmp rpt2 final:display num mov ah,4ch int 21h end OUTPUT ENTER THE NUMBERS : 1 5 2 4 3$" ENTERED NUMBERS :15243 AFTER SORTING : 1 2 3 4 5

58

LEX PROGRAMS

59

1.Programtorecognizeintegers PROGRAM %{ #include<stdio.h> %} digit[09] %optionnoyywrap %% {digit}+{printf("INTEGER\n");exit(0);} .{printf("NOTANINTEGER\n");exit(0);} %% intmain(void) { yylex(); return0; } OUTPUT ./a.out hi NOTANINTEGER ./a.out 1 INTEGER

60

2.writealexprogramtoreognizefloatingpointnumbers. PROGRAM %{ #include<stdio.h> %} digit[09] char[azAZ] %optionnoyywrap %% {digit}*"."{digit}*{printf("FLOATVALUE\n");exit(0);} .{printf("NOTAFLOATVALUE\n");exit(0);} %% intmain(void) { yylex(); return0; } OUTPUT 3.14 FLOATVALUE

61

3.Writealexprogramtorecognizeidentifiers.Anidentifiershouldstartwithaletterandmaybe followedbylettersordigits. PROGRAM %{ #include<stdio.h> %} ID[azAZ][azAZ09]* %optionnoyywrap %% {ID}{printf("IDENTIFIER\n");exit(0);} .{printf("NOTANIDENTIFIER\n");exit(0);} %% intmain(void) { yylex(); return0; }

OUTPUT ./a.out id12 IDENTIFIER ./a.out 12is NOTANIDENTIFIER

62

4.Writealexprogramtorecognizestringsendingwith"abb". PROGRAM %{ #include<stdio.h> %} ID[azAZ09,]* %optionnoyywrap %% {ID}"a""b""b"{printf("STRINGENDINGWITHabb\n");exit(0);} {ID}{printf("NOTENDINGWITHabb\n");exit(0);} %% intmain(void) { yylex(); return0; } OUTPUT ./a.out helloabb STRINGENDINGWITHabb ./a.out haiabbbbb NOTENDINGWITHabb

63

5.Writealexprogramtoselectonlylinesthatbeginwith//andignoreallothers. PROGRAM %{ #include<stdio.h> %} %optionnoyywrap %% "//".*{printf("COMMENTLINE\n");exit(0);} .{printf("NOTCOMMENTLINE\n");exit(0);} %% intmain(void) { yylex(); return0; } OUTPUT ./a.out hai//ji NOTCOMMENTLINE ./a.out //comments COMMENTLINE

64

6.Writealexprogramthatconvertsordisplaythehexaequivalentofadecimalnumber. PROGRAM %{ #include<stdio.h> intn,b[10],i=0,j; %} digit[09] %optionnoyywrap %% {digit}*{ n=atoi(yytext); while(n>15){ b[i]=n%16;n=n/16;i++; } b[i]=n; j=i; do { switch(b[j]) { case10:printf("A"); break; case11:printf("B");break; case12:printf("C");break; case13:printf("D");break; case14:printf("E");break; case15:printf("F");break; default:printf("%d",b[j]); break; } j; }while(j>=0); printf("\n"); exit(0); } .{exit(0);} %% intmain(void) { yylex(); return0; }

OUTPUT ./a.out 11 B

65

7.Writealexprogramthatdisplaysthenumbersforromanletters. PROGRAM %{ #include<stdio.h> inttotal=0; %} WS [\t]+ %optionnoyywrap %% I total+=1; IV total+=4; V total+=5; IX total+=9; X total+=10; XL total+=40; L total+=50; XC total+=90; C total+=100; CD total+=400; D total+=500; CM total+=900; M total+=1000; {WS} | \n returntotal; %% main(){ ints; s=yylex(); printf("%d\n",s); return0; } OUTPUT ./a.out IV 4

66

8.Writealexprogramtocountnumberoflines,wordsandcharacters. PROGRAM %{ intchars=0; intwords=0; intlines=0;

%} %optionnoyywrap %% \n{lines++;} [\t]{chars++;} [azAZ09]{chars++;} [azAZ09]/[\n]{words++;chars++;} .{chars++;} %% main() { yylex(); printf("\nCHARACTERS=%d\n",chars); printf("WORDS=%d\n",words); printf("LINES=%d\n",lines); } OUTPUT ./a.out hihello howru CHARACTERS=15 WORDS=5 LINES=2

You might also like