You are on page 1of 83

VALLURUPALLI NAGESWARA RAO VIGNANA JYOTHI

INSTITUTE OF ENGINEERING AND TECHNOLOGY


(AUTONOMOUS)
BACHUPALLY(SO), NIZAMPET, HYDERABAD-5000090.

LABORATORY
LABORATORYRECORD
MANUAL

SUBJECT: CN & CD LABORATORY

DEPARTMENT OF INFORMATION TECHNOLOGY


COMPUTER NETWORKS:

S.NO NAME OF THE PROGRAM


1 Bit stuffing
2 Bit de-stuffing
3 Character stuffing
4 Character de-stuffing
5 CRC
6 Networking commands
7 Establishing a network between computers
8 Configuring FTP Server for file sharing
9 Implement Dijkstra ‘s algorithm
1. Aim: Write a program for bit stuffing.

Program:
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}
Output:
2. Aim: Write a program for bit de-stuffing.

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

int main()
{
int a[100],b[1000],n;
int i=0,c=0,j=0,k=0;

scanf("%d",&n);

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n");

for(i=0;i<n;i++)
{
if(c==5)
{
if(a[i]==1)
{
b[j]=a[i];
j++;
c=0;
}
}
else
{
if(a[i]==1)
{
b[j] = a[i];
j++;
c++;
}
else if(a[i]==0)
{
b[j]=a[i];
j++;
}
}
}
printf("After destuffing :: ");
for(int i=0;i<j;i++)
{
printf("%d ",b[i]);
}
getch();
}

Output:
3. Aim: Write a program for character stuffing.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char c[1000],d[1000],t[1000];
int i,j=0,len;

gets(c);
len = strlen(c);

for(i=0;i<len;i++)
{
if(c[i]=='f' && c[i+1]=='l' && c[i+2]=='a' && c[i+3]=='g')
{
d[j++] = 'e';
d[j++] = 's';
d[j++] = 'c';
}
if(c[i]=='e' && c[i+1] == 's' && c[i+2]=='c')
{
d[j++]='e';
d[j++] = 's';
d[j++] = 'c';
d[j++] = 'e';
}
else
{
d[j++] = c[i];
}}
for(i=0;i<j;i++)
{
printf("%c ",d[i]);
}
}
Output:
4. Aim: Write a program for character de-stuffing.

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char c[1000],d[1000],t[1000];
int i,j=0,len;
gets(c);
len = strlen(c);
for(i=0;i<len;i++){
if(c[i]=='e' && c[i+1]=='s' && c[i+2]=='c' && c[i+3]=='e' && c[i+4]=='s' &&
c[i+5]=='c'){
d[j++] = 'e';
d[j++] = 's';
i = i+5; }
if(c[i]=='e' && c[i+1] == 's' && c[i+2]=='c' && c[i+3]=='f' && c[i+4]=='l' &&
c[i+5]=='a' && c[i+6]=='g')
{
d[j++]='f';
d[j++] = 'l';
d[j++] = 'a';
d[j++] = 'g';
i=i+6;
}
else
{
d[j++] = c[i];
}
}
for(i=0;i<j;i++)
{
printf("%c ",d[i]);
}
}

Output:
5. Aim: Write a program for CRC.

Program:

#include<stdio.h>
#include<string.h>
int getInt(char ch){
if(ch == '1')
return 1;
return 0;
}

void generateQuotient(int data[1000],int code[1000],int d,int c){


int i,j;
int data1[1000];
for(i=0;i<d;i++){
data1[i] = data[i];
}
int temp[1000];
for(i=0;i<d-c+1;i++){
for(j=0;j<c;j++){
temp[j]=data1[i]*code[j];
}
for(j=0;j<c;j++){
data1[i+j] = data1[i+j]^temp[j];
}
}
printf("\nRemainder : ");
for(i=d-c+1;i<d;i++){
data[i] = data1[i];
printf("%d",data[i]);
}
}

int main(){
int flag=0;
int data[1000],code[1000],i;
char data_char[1000],code_char[1000];
printf("\nEnter data in binary : ");
gets(data_char);
printf("\nEnter code in binary : ");
gets(code_char);
int d = strlen(data_char);
int c = strlen(code_char);
int l = c-1;
char temp[100];
for(i=0;i<l;i++){
temp[i]='0';
}
strcat(data_char,temp);
d=d+l;
for(i=0;i<d;i++)
data[i]=getInt(data_char[i]);
for(i=0;i<d;i++)
code[i]=getInt(code_char[i]);
printf("\nOriginal data to be sent after adding zeroes : ");
for(i=0;i<d;i++)
printf("%d",data[i]);
generateQuotient(data,code,d,c);
printf("\nCode sent to the reciever : ");
for(i=0;i<d;i++)
printf("%d",data[i]);
generateQuotient(data,code,d,c);
for(i=d-c+1;i<d;i++){
if(data[i]!=0){
flag=1;
}
}
if(flag==1)
printf("\nError detected");
else
printf("\nNo error detected");
return 0;
}

Output:
6. Aim: Basic networking commands.

Commands:
tracet: It is a network diagnostic tool used to track the pathway taken by packet
Syntax tracert [options] target-name
Options:
-d Do not resolve addresses to hostnames.
-h maximum_hops Maximum number of hops to search for target.
-j host-list Loose source route along host-list (IPv4-only).
-w timeout Wait timeout milliseconds for each reply.
-R Trace round-trip path (IPv6-only).
-S srcaddr Source address to use (IPv6-only).
-4 Force using IPv4.
-6 Force using IPv6.
tracert Commands:
Ping: It is used as a test to see if a network device is reachable
Syntax: ping [option] target-name

Options :
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP
Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
Per RFC 5095 the use of this routing header has been
deprecated. Some systems may drop echo requests if
this header is used.
-S srcaddr Source address to use.
-c compartment Routing compartment identifier.
-p Ping a Hyper-V Network Virtualization provider address.
-4 Force using IPv4.
-6 Force using IPv6.
ping commands:
Arp: Displays and modifies the IP to Physical address translation tables used by
address resolution protocol.
Syntax: arp [option]
Option:

-a Displays current ARP entries by interrogating the current


protocol data. If inet_addr is specified, the IP and Physical
addresses for only the specified computer are displayed. If
more than one network interface uses ARP, entries for each ARP
table are displayed.
-g Same as -a.
-v Displays current ARP entries in verbose mode. All invalid
Entries and entries on the loop-back interface will be shown.
inet_addr Specifies an internet address.
-N if_addr Displays the ARP entries for the network interface specified
by if_addr.
-d Deletes the host specified by inet_addr. inet_addr may be
wildcarded with * to delete all hosts.
-s Adds the host and associates the Internet address inet_addr
with the Physical address eth_addr. The Physical address is
given as 6 hexadecimal bytes separated by hyphens. The entry
is permanent.
eth_addr Specifies a physical address.
if_addr If present, this specifies the Internet address of the
interface whose address translation table should be modified.
If not present, the first applicable interface will be used.

arp commands:
Netstat: Displays protocol statistics and current TCP/IP network connection

Syntax: netstat [option]


Options:
-a Displays all connections and listening ports.
-b Displays the executable involved in creating each connection or
listening port. In some cases well-known executables host
multiple independent components, and in these cases the
sequence of components involved in creating the connection
or listening port is displayed. In this case the executable
name is in [] at the bottom, on top is the component it called,
and so forth until TCP/IP was reached. Note that this option
can be time-consuming and will fail unless you have sufficient
permissions.
-e Displays Ethernet statistics. This may be combined with the -s
option.
-f Displays Fully Qualified Domain Names (FQDN) for foreign
addresses.
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.
-p proto Shows connections for the protocol specified by proto; proto
may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s
option to display per-protocol statistics, proto may be any of:
IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-q Displays all connections, listening ports, and bound
nonlistening TCP ports. Bound nonlistening ports may or may not
be associated with an active connection.
-r Displays the routing table.
-s Displays per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
the -p option may be used to specify a subset of the default.
-t Displays the current connection offload state.
-x Displays NetworkDirect connections, listeners, and shared
endpoints.
-y Displays the TCP connection template for all connections.
Cannot be combined with the other options.
interval Redisplays selected statistics, pausing interval seconds
between each display. Press CTRL+C to stop redisplaying
statistics. If omitted, netstat will print the current
configuration information once.

Netstat commands:
Ipconfig: Displays all TCP/IP network configuration values
Syntax: ipconfig [options]
Options:
/? Display this help message
/all Display full configuration information.
/release Release the IPv4 address for the specified adapter.
/release6 Release the IPv6 address for the specified adapter.
/renew Renew the IPv4 address for the specified adapter.
/renew6 Renew the IPv6 address for the specified adapter.
/flushdns Purges the DNS Resolver cache.
/registerdns Refreshes all DHCP leases and re-registers DNS names
/displaydns Display the contents of the DNS Resolver Cache.
/showclassid Displays all the dhcp class IDs allowed for adapter.
/setclassid Modifies the dhcp class id.
/showclassid6 Displays all the IPv6 DHCP class IDs allowed for adapter.
/setclassid6 Modifies the IPv6 DHCP class id.

Ipconfig commands:
Hostname: Print the name of the current host
Syntax: hostname
Hostname command:

Route: Manipulates network routing table.


Syntax: route [option]
Options:
-f Clears the routing tables of all gateway entries. If this is
used in conjunction with one of the commands, the tables are
cleared prior to running the command.

-p When used with the ADD command, makes a route persistent across
boots of the system. By default, routes are not preserved
when the system is restarted. Ignored for all other commands,
which always affect the appropriate persistent routes.

-4 Force using IPv4.


-6 Force using IP

Route commands:
Nslookup: Nslookup is the name of the program that lets and internet server admin
or any computer user to enter an host name.
Nslookup Command:
Pathping: It provides useful information about network latency and network loss.
Syntax: pathping [options] target-name
Optoins:
-g host-list Loose source route along host-list.
-h maximum_hops Maximum number of hops to search for target.
-i address Use the specified source address.
-n Do not resolve addresses to hostnames.
-p period Wait period milliseconds between pings.
-q num_queries Number of queries per hop.
-w timeout Wait timeout milliseconds for each reply.
-4 Force using IPv4.
-6 Force using IPv6.

Pathping commands:
Getmac: This tool enables an administrator to display the MAC address.
Syntax: mac [option]
Options:
/S system Specifies the remote system to connect to.
/U [domain\]user Specifies the user context under
which the command should execute.
/P [password] Specifies the password for the given
user context. Prompts for input if omitted.
/FO format Specifies the format in which the output
is to be displayed.
Valid values: "TABLE", "LIST", "CSV".
/NH Specifies that the "Column Header" should
not be displayed in the output.
Valid only for TABLE and CSV formats.
/V Specifies that verbose output is displayed.
/? Displays this help message.

Getmac Commands:
7. Aim: Write about Establishing a network between computers.

Two computers can be easily connected to share the files between them or to share
the internet, printer between them. The process is usually simple and can be done
with a few hardware devices and a bit of software knowledge. This article will tell
you about various ways to connect two computers.

Follow these steps to connect two computers having a Windows Operating system to
share the internet:

Step 1: Connect two Computers using an ethernet cable.

Step 3: Click on option Change Adapter Setting in the upper-left side of the window.

Step 4: Select both the Wi-Fi connection and the Ethernet connection and Right-click
the Wi-Fi connections.

Step 5: Click on Bridge Connections. After some time, your computer’s Wi-Fi will be
shared with the other computer.

Follow these steps to connect two computers having a Windows Operating system to
share the files between them:

Step 1: Connect two Computers using an ethernet cable.

Step 2: Click on Start->Control Panel->Network and Internet->Network and Sharing


Centre.

Step 3: Click on option Change Advanced Sharing Settings in the upper-left side of
the window.

Step 4: Turn on file sharing. Check the Turn on file and printer sharing.

Step 5: To Share a folder follow these steps-

 Go to the folder’s location.


 Select the folder you want to share.
 Click on the Share tab and then on specific people
 Select Everyone from the drop-down menu.
 Click Share then Done

Step 6: Open the File Explorer on another computer.

Step 7: On the left side below the Network heading you will find your first computer
name. Click on the name.

Step 8: Copy the shared folder onto your second computer.


8. Aim: Write about Configuring FTP Server for file sharing

After installing the required components, you can proceed to configure an FTP server
on the computer, which involves creating a new FTP site, setting up firewall rules,
and allowing external connections.

Setting up an FTP site

To set up an FTP site, do the following:

1. Open Control Panel.


2. Click on System and Security.
3. Click on Administrative Tools.
4. Double-click the Internet Information Services (IIS) Manager shortcut.
5. On the "Connections" pane, right-click Sites, and select the Add FTP Site
option.
6. In the FTP site name, type a short descriptive name for the server.
7. In the "Content Directory" section, under "Physical path," click the button on
the right to locate the folder you want to use to store your FTP files.
8. Click the Next button.
9. Use the default Binding settings selections.
10. Check the Start FTP site automatically option.
11. In the "SSL" section, check the No SSL option.
12. Click the Next button.
13. In the "Authentication" section, check the Basic option.
14. In the "Authorization" section, use the drop-down menu, and select Specified
user option.
15. Type the email address of your Windows 10 account or local account name to
allow yourself access to the FTP server.
16. Check the Read and Write options.
17. click the Finish button.

After completing the steps, the FTP site should now be operational on your
computer.
9. Aim: Implement Dijkstra ‘s algorithm to compute the Shortest path through a graph.

Program:

#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] <
dist[v]) dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}

Output:
COMPILER DESIGN:

INDEX

S.NO NAME OF THE PROGRAM


1 Keywords in a string.
2 String is a constant or not.
3 String is a comment or not.
4 String is an identifier or not.
5 Lexical analyzer.
6 Regular expression.
7 Left recursion.
8 Find first.
9 Find Follow.
10 Parsing table.
11 Bottom up parser.
1. Aim: Write a program to detect keywords in a given string.

Program:
#include<stdio.h>
#include<string.h>

void patternMatch(char ch[15],char text[15]){


int M = strlen(ch);
int N = strlen(text);

for(int i=0;i<N-M;i++){
int j;
for(j=0;j<M;j++)
if(text[i+j]!=ch[j])
break;
if(j==M)
printf("%s\n",ch);
}
}

int main(){
char key_words[32][100]= {"auto","break","case","char","const",

"continue","default","do","double","else","enum",

"extern","float","for","goto","if","int","long","register",

"return","short","signed","sizeof","static","struct","switch",

"typedef","union","unsigned","void","volatile","while"};
char text[100];
printf("\nEnter text [Specify atleast one blankspace after a word] : \n");
gets(text);

for(int i=0;i<32;i++){
char ch[15];
int j=0;
int c=0;
strcpy(ch,key_words[i]);
patternMatch(ch,text);
}
}

Output:
2. Aim: Write a program to check for given string is a constant or not.

Program:
#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main(){
char ch[100];
printf("\nEnter a string/value : ");
gets(ch);
int flag = 0;
for(int i=0;i<strlen(ch);i++){
if(isdigit(ch[i]) || (ch[i] == '.' && ch[i-1] != '.')){
continue;
}
else{
flag =1;
break;
}
}
if(flag == 1)
printf("\n It is not a constant");
else
printf("\n It is a constant");

return 0;
}

Output:
3. Aim: Write a program to check if a given string is a comment

Program:

#include<bits/stdc++.h>
#include<string.h>
using namespace std;
int main()

{
string a;
cout<<"Enter a string : ";
cin>>a;

if(a[0]=='/' && a[1]=='/')


cout<<"Given string is a comment"<<endl;
else if(a[0]=='/' && a[1]=='*' && a[a.length()-1] =='/' && a[a.length()-
2]=='*')
cout<<"Given string is a comment"<<endl;
else
cout<<"Given string is not a comment"<<endl;
}

Output:
4. Aim: Write a program to test whether the given string is a identifier or not.

Program:

#include<bits/stdc++.h>
#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
string s;

cout<<"Enter a string : ";

cin>>s;
int c=0;

for(int i=0;i<s.length();i++)
{
if(i==0)
{

if(isalpha(s[i]) || s[i] == '_' )


{

c++;
}
}
else
{
if(isalpha(s[i])|| isdigit(s[i]) || s[i]=='_')
{
c++;
}
}
}

if(c==s.length())
cout<<"Valid identifier";
else
cout<<"Invalid identifier";
}

Output:
5. Aim: Design a lexical analyzer for the given language. The lexical analyzer should
ignore redundant spaces, tabs and new lines and ignore comments. Although the
syntax specification states that identifiers can be to arbitrarily long you may restrict
the length to reasonable values.

Program:

#include<iostream>
#include<string.h>
#include<ctype.h>

using namespace std;


int top = 0;
char array[1000];

void push(char ch){


if(top == 1000)
printf("Stack is full ");
else{
array[top] = ch;
top++;
}
}

bool isOperator(char ch){


if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=' || ch=='!' || ch == '^' || ch == '%')
return true;
return false;
}

bool isSpecial(char ch){


if(ch == ',' || ch == ';' || ch == '@' ||
ch == '#' || ch == '$' || ch == '(' || ch == ')' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}' )
return true;
return false;
}

void isKeyWord(){
int flag =0;
char text[1000];
for(int i=0;i<top;i++)
text[i]=array[i];
char key_words[32][100]= {"auto","break","case","char","const",

"continue","default","do","double","else","enum",

"extern","float","for","goto","if","int","long","register",

"return","short","signed","sizeof","static","struct","switch",

"typedef","union","unsigned","void","volatile","while"};
for(int i=0;i<32;i++){
char ch[1000];
strcpy(ch,key_words[i]);
if(strcmp(text,ch)==0){
flag = 1;
break;
}

}
if(flag == 1)
printf("\nKeyWords ------------------ %s",text);
else
printf("\nIdentifier --------------- %s",text);
flag =0;
for(int i=0;i<top;i++)
text[i] = '\0';
top =0;
}

int main(){
char arr[1000];
int i;
for( i = 0; i < sizeof(arr); i +=2 ){
scanf("%c%c",&arr[i],&arr[i+1]);
if( arr[i] == '\n' && arr[i+1] == '\n' )
break;
}
for(int i=0;arr[i]!='\0';i++){
if(arr[i]=='/' && arr[i+1]=='/'){
while(arr[i]!='\n')
i++;
continue;
}
if(arr[i] == '/' && arr[i+1]=='*'){
while(true){
if(arr[i]=='*'&&arr[i+1]=='/')
break;

i++;
}
i+=2;
}
if(isalpha(arr[i]) || arr[i]=='_'){
push(arr[i]);
}
if(isdigit(arr[i])){
if(top == 0){
printf("\nConstant --------------- ");
while(isdigit(arr[i])){
printf("%c",arr[i++]);
}}
else{
push(arr[i]);
} }

if(arr[i]==' ' || isSpecial(arr[i])||isOperator(arr[i]) || arr[i] == ';'){


if(top!=0)
isKeyWord();
if(isSpecial(arr[i]))
printf("\nSpecial Symbol ------------- %c",arr[i]);
if(isOperator(arr[i]))
printf("\nOperator ---------------- %c",arr[i]);
}}
return 0;
}
Output:
6. Aim: Write a program to recognize the strings under a*, a*b+, abb.

Program:
//C++ Program to recognize the strings under a*, a*b+, abb.
#include<bits/stdc++.h>
using namespace std;

int lang1(string s)

{
int ct = 0;

if(s[0]='E' && s.length()==1)


{
return 1;
}
else{
for(int i=0;i<s.length();i++)
{

if(s[i]=='a')
{
ct++;
}
}
if(ct==s.length())
return 1;
else
return 0;
}
}
int lang2(string s)

{
int ct=0,flag=0;
for(int i=0;i<s.length();i++)
{
if(s[i]=='a' && flag==0)
{
ct++;
}
if(s[i]=='b')
ct++;
if(s[i]=='b')
flag=1;
}
if(ct==s.length() && flag == 1)
{
return 1;
}
else
return 0;
}

int lang3(string s)
{
int len = 3;

if(s.length()==3){
if(s[0]=='a' && s[1] == 'b' && s[2] =='b')
return 1; }
else

return 0;
}
int main()
{
string s;
int x,flag=0;
cout<<"Enter the String :: "<<endl;
cin>>s;

x = lang1(s);
if(x){
cout<<"String "<<s<<" is in a*"<<endl;
flag =1;}
x = lang2(s);
if(x){
cout<<"String "<<s<<" is in a*b+"<<endl;
flag=1;}
x = lang3(s);
if(x){
cout<<"String "<<s<<" is in abb"<<endl;
flag=1; }

if(flag==0)
cout<<"String "<<s<<" is invalid. "<<endl;
}

Output:
7. Aim: Write a program to eliminate left recursion for the given productions.

Program:

#include<iostream>
#include<string.h>
using namespace std;

checkProd(char ch[100], char NT) {


if (ch[0] == NT) {
cout << NT << "`" << "-" << ">";
for (int i = 1; i < strlen(ch); i++)
cout << ch[i];
cout << NT << "`";
cout << endl;
} else {
cout << NT << "-" << ">" << ch << NT << "`";
cout << endl;
}
}
void checkLeft(char prod[100]) {
char NT = prod[0];
int flag = 0;
for (int i = 3; i < strlen(prod); i++) {
if (prod[i] == NT && (prod[i - 1] == '|' || prod[i - 1] == '>'))
flag = 1;
}
if (flag == 0) {
cout << prod << endl;
} else {
int lflag = 0;
char temp[100];
int k = 0;
for (int i = 3; i <= strlen(prod); i++) {
if (prod[i] == '|' || prod[i] == '\0') {
checkProd(temp, NT);
for (int j = 0; j < k; j++)
temp[j] = '\0';
k = 0;
continue;
}
temp[k++] = prod[i];
}
cout << NT << "`->" << "Epsilon" << endl;
}
}
int main() {
char ch[100];
int n;
cout << "Enter the number of productions : ";
cin >> n;
cout << "Enter the productions : " << endl;
char temp[100][100];
for (int i = 0; i < n; i++) {
cin >> ch;
strcpy(temp[i], ch);
}
cout << "The given grammer is : ";
for (int i = 0; i < n; i++) {
cout << temp[i] << endl;
}
for (int i = 0; i < n; i++) {
checkLeft(temp[i]);
cout << endl;
}}
Output:
8. Aim: Write a program to find the first of the given productions.

Program:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<iostream>

using namespace std;

void followfirst(char, int, int);


void follow(char c);
void findfirst(char, int, int);

int count, n = 0;
char calc_first[10][100];
char calc_follow[10][100];
int m = 0;
char production[10][10];
char f[10], first[10];
int k;
char ck;
int e;

int main(int argc, char ** argv) {


int jm = 0;
int km = 0;
int i, choice;
char c, ch;
count = 8;
char s[10];
int x;
cout << "Enter no of productions :: " << endl;
cin >> x;

for (int k = 0; k < x; k++) {


cin >> s;
strcpy(production[k], s);
}

int kay;
char done[count];
int ptr = -1;
for (k = 0; k < count; k++) {
for (kay = 0; kay < 100; kay++) {
calc_first[k][kay] = '!';
}
}
int point1 = 0, point2, xxx;

for (k = 0; k < count; k++) {


c = production[k][0];
point2 = 0;
xxx = 0;

for (kay = 0; kay <= ptr; kay++)


if (c == done[kay])
xxx = 1;

if (xxx == 1)
continue;

findfirst(c, 0, 0);
ptr += 1;

done[ptr] = c;
printf("\n First(%c) = { ", c);
calc_first[point1][point2++] = c;

for (i = 0 + jm; i < n; i++) {


int lark = 0, chk = 0;

for (lark = 0; lark < point2; lark++) {

if (first[i] == calc_first[point1][lark]) {
chk = 1;
break;
}
}
if (chk == 0) {
printf("%c, ", first[i]);
calc_first[point1][point2++] = first[i];
}
}
printf("}\n");
jm = n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;

for (k = 0; k < count; k++) {


for (kay = 0; kay < 100; kay++) {
calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land = 0;
for (e = 0; e < count; e++) {
ck = production[e][0];
point2 = 0;
xxx = 0;

for (kay = 0; kay <= ptr; kay++)


if (ck == donee[kay])
xxx = 1;

if (xxx == 1)
continue;
land += 1;

follow(ck);
ptr += 1;

donee[ptr] = ck;
printf(" Follow(%c) = { ", ck);
calc_follow[point1][point2++] = ck;

for (i = 0 + km; i < m; i++) {


int lark = 0, chk = 0;
for (lark = 0; lark < point2; lark++) {
if (f[i] == calc_follow[point1][lark]) {
chk = 1;
break;
}
}
if (chk == 0) {
printf("%c, ", f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\n");
km = m;
point1++;
}
}

void follow(char c) {
int i, j;

if (production[0][0] == c) {
f[m++] = '$';
}
for (i = 0; i < 10; i++) {
for (j = 2; j < 10; j++) {
if (production[i][j] == c) {
if (production[i][j + 1] != '\0') {

followfirst(production[i][j + 1], i, (j + 2));


}

if (production[i][j + 1] == '\0' && c != production[i][0]) {

follow(production[i][0]);
}
}
}
}
}

void findfirst(char c, int q1, int q2) {


int j;
if (!(isupper(c))) {
first[n++] = c;
}
for (j = 0; j < count; j++) {
if (production[j][0] == c) {
if (production[j][2] == '#') {
if (production[q1][q2] == '\0')
first[n++] = '#';
else if (production[q1][q2] != '\0' &&
(q1 != 0 || q2 != 0)) {
findfirst(production[q1][q2], q1, (q2 + 1));
} else
first[n++] = '#';
} else if (!isupper(production[j][2])) {
first[n++] = production[j][2];
} else {
findfirst(production[j][2], j, 3);
}
}
}
}

void followfirst(char c, int c1, int c2) {


int k;

if (!(isupper(c)))
f[m++] = c;
else {
int i = 0, j = 1;
for (i = 0; i < count; i++) {
if (calc_first[i][0] == c)
break;
}
while (calc_first[i][j] != '!') {
if (calc_first[i][j] != '#') {
f[m++] = calc_first[i][j];
} else {
if (production[c1][c2] == '\0') {

follow(production[c1][0]);
} else {
followfirst(production[c1][c2], c1, c2 + 1);
}
}
j++;
}
}
}

Output:
9. Aim: Write a program to find the first of the given productions.

Program:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<iostream>

using namespace std;

void followfirst(char, int, int);


void follow(char c);
void findfirst(char, int, int);

int count, n = 0;
char calc_first[10][100];
char calc_follow[10][100];
int m = 0;
char production[10][10];
char f[10], first[10];
int k;
char ck;
int e;

int main(int argc, char ** argv) {


int jm = 0;
int km = 0;
int i, choice;
char c, ch;
count = 8;
char s[10];
int x;
cout << "Enter no of productions :: " << endl;
cin >> x;

for (int k = 0; k < x; k++) {


cin >> s;
strcpy(production[k], s);
}

int kay;
char done[count];
int ptr = -1;
for (k = 0; k < count; k++) {
for (kay = 0; kay < 100; kay++) {
calc_first[k][kay] = '!';
}
}
int point1 = 0, point2, xxx;

for (k = 0; k < count; k++) {


c = production[k][0];
point2 = 0;
xxx = 0;

for (kay = 0; kay <= ptr; kay++)


if (c == done[kay])
xxx = 1;

if (xxx == 1)
continue;

findfirst(c, 0, 0);
ptr += 1;

done[ptr] = c;
printf("\n First(%c) = { ", c);
calc_first[point1][point2++] = c;

for (i = 0 + jm; i < n; i++) {


int lark = 0, chk = 0;

for (lark = 0; lark < point2; lark++) {

if (first[i] == calc_first[point1][lark]) {
chk = 1;
break;
}
}
if (chk == 0) {
printf("%c, ", first[i]);
calc_first[point1][point2++] = first[i];
}
}
printf("}\n");
jm = n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;

for (k = 0; k < count; k++) {


for (kay = 0; kay < 100; kay++) {
calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land = 0;
for (e = 0; e < count; e++) {
ck = production[e][0];
point2 = 0;
xxx = 0;

for (kay = 0; kay <= ptr; kay++)


if (ck == donee[kay])
xxx = 1;

if (xxx == 1)
continue;
land += 1;

follow(ck);
ptr += 1;

donee[ptr] = ck;
printf(" Follow(%c) = { ", ck);
calc_follow[point1][point2++] = ck;

for (i = 0 + km; i < m; i++) {


int lark = 0, chk = 0;
for (lark = 0; lark < point2; lark++) {
if (f[i] == calc_follow[point1][lark]) {
chk = 1;
break;
}
}
if (chk == 0) {
printf("%c, ", f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\n");
km = m;
point1++;
}
}

void follow(char c) {
int i, j;

if (production[0][0] == c) {
f[m++] = '$';
}
for (i = 0; i < 10; i++) {
for (j = 2; j < 10; j++) {
if (production[i][j] == c) {
if (production[i][j + 1] != '\0') {

followfirst(production[i][j + 1], i, (j + 2));


}

if (production[i][j + 1] == '\0' && c != production[i][0]) {

follow(production[i][0]);
}
}
}
}
}

void findfirst(char c, int q1, int q2) {


int j;
if (!(isupper(c))) {
first[n++] = c;
}
for (j = 0; j < count; j++) {
if (production[j][0] == c) {
if (production[j][2] == '#') {
if (production[q1][q2] == '\0')
first[n++] = '#';
else if (production[q1][q2] != '\0' &&
(q1 != 0 || q2 != 0)) {
findfirst(production[q1][q2], q1, (q2 + 1));
} else
first[n++] = '#';
} else if (!isupper(production[j][2])) {
first[n++] = production[j][2];
} else {
findfirst(production[j][2], j, 3);
}
}
}
}

void followfirst(char c, int c1, int c2) {


int k;

if (!(isupper(c)))
f[m++] = c;
else {
int i = 0, j = 1;
for (i = 0; i < count; i++) {
if (calc_first[i][0] == c)
break;
}
while (calc_first[i][j] != '!') {
if (calc_first[i][j] != '#') {
f[m++] = calc_first[i][j];
} else {
if (production[c1][c2] == '\0') {

follow(production[c1][0]);
} else {
followfirst(production[c1][c2], c1, c2 + 1);
}
}
j++;
}
}
}

Output:
10. Aim: Write a program to find parsing table of the given productions.

Program:

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

void followfirst(char , int , int);


void findfirst(char , int , int);
void follow(char c);

int count,n=0;
char calc_first[10][100];
char calc_follow[10][100];
int m=0;
char production[10][10], first[10];
char f[10];
int k;
char ck;
int e;

int main(int argc,char **argv)


{
int jm=0;
int km=0;
int i,choice;
char c,ch;
printf("How many productions ? :");
scanf("%d",&count);
printf("\nEnter %d productions in form A=B where A and B are grammar
symbols :\n\n",count);
for(i=0;i<count;i++)
{
scanf("%s%c",production[i],&ch);
}
int kay;
char done[count];
int ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_first[k][kay] = '!';
}
}
int point1 = 0,point2,xxx;
for(k=0;k<count;k++)
{
c=production[k][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(c == done[kay])
xxx = 1;
if (xxx == 1)
continue;
findfirst(c,0,0);
ptr+=1;
done[ptr] = c;
printf("\n First(%c)= { ",c);
calc_first[point1][point2++] = c;
for(i=0+jm;i<n;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (first[i] == calc_first[point1][lark]){
chk = 1;
break;
}
}
if(chk == 0){
printf("%c, ",first[i]);
calc_first[point1][point2++] = first[i];
}
}
printf("}\n");
jm=n;
point1++;
}
printf("\n");
printf("-----------------------------------------------\n\n");
char donee[count];
ptr = -1;
for(k=0;k<count;k++){
for(kay=0;kay<100;kay++){
calc_follow[k][kay] = '!';
}
}
point1 = 0;
int land = 0;
for(e=0;e<count;e++)
{
ck=production[e][0];
point2 = 0;
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == donee[kay])
xxx = 1;
if (xxx == 1)
continue;
land += 1;
follow(ck);
ptr+=1;
donee[ptr] = ck;
printf(" Follow(%c) = { ",ck);
calc_follow[point1][point2++] = ck;
for(i=0+km;i<m;i++){
int lark = 0,chk = 0;
for(lark=0;lark<point2;lark++){
if (f[i] == calc_follow[point1][lark]){
chk = 1;
break;
}
}
if(chk == 0){
printf("%c, ",f[i]);
calc_follow[point1][point2++] = f[i];
}
}
printf(" }\n\n");
km=m;
point1++;
}
char ter[10];
for(k=0;k<10;k++){
ter[k] = '!';}
int ap,vp,sid = 0;
for(k=0;k<count;k++){
for(kay=0;kay<count;kay++){
if(!isupper(production[k][kay]) && production[k][kay]!= '#' &&
production[k][kay] != '=' && production[k][kay] != '\0'){
vp = 0;
for(ap = 0;ap < sid; ap++){
if(production[k][kay] == ter[ap]){
vp = 1;
break; }}
if(vp == 0){
ter[sid] = production[k][kay];
sid ++;}}}}
ter[sid] = '$';
sid++;
printf("\n\t\t\t\t\t\t\t The LL(1) Parsing Table for the above grammer :-");
printf("\n\t\t\t\t\t\t\t^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^\n");
printf("\n\t\t\t===================================================
==================================================================
\n");
printf("\t\t\t\t|\t");
for(ap = 0;ap < sid; ap++){
printf("%c\t\t",ter[ap]);
}
printf("\n\t\t\t===================================================
==================================================================
\n");
char first_prod[count][sid];
for(ap=0;ap<count;ap++){
int destiny = 0;
k = 2;
int ct = 0;
char tem[100];
while(production[ap][k] != '\0'){
if(!isupper(production[ap][k])){
tem[ct++] = production[ap][k];
tem[ct++] = '_';
tem[ct++] = '\0';
k++;
break;
}
else{
int zap=0;
int tuna = 0;
for(zap=0;zap<count;zap++){
if(calc_first[zap][0] == production[ap][k]){
for(tuna=1;tuna<100;tuna++){
if(calc_first[zap][tuna] != '!'){
tem[ct++] =
calc_first[zap][tuna];
}
else
break;
}
break;
}
}
tem[ct++] = '_';
}
k++;
}
int zap = 0,tuna;
for(tuna = 0;tuna<ct;tuna++){
if(tem[tuna] == '#'){
zap = 1;
}
else if(tem[tuna] == '_'){
if(zap == 1){
zap = 0;
}
else
break;
}
else{
first_prod[ap][destiny++] = tem[tuna];
}}}
char table[land][sid+1];
ptr = -1;
for(ap = 0; ap < land ; ap++){
for(kay = 0; kay < (sid + 1) ; kay++){
table[ap][kay] = '!';
}
}
for(ap = 0; ap < count ; ap++){
ck = production[ap][0];
xxx = 0;
for(kay = 0; kay <= ptr; kay++)
if(ck == table[kay][0])
xxx = 1;
if (xxx == 1)
continue;
else{
ptr = ptr + 1;
table[ptr][0] = ck;
}
}
for(ap = 0; ap < count ; ap++){
int tuna = 0;
while(first_prod[ap][tuna] != '\0'){
int to,ni=0;
for(to=0;to<sid;to++){
if(first_prod[ap][tuna] == ter[to]){
ni = 1;
}
}
if(ni == 1){
char xz = production[ap][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != first_prod[ap][tuna]){
vz = vz + 1;
}
table[cz][vz+1] = (char)(ap + 65);
}
tuna++;
}
}
for(k=0;k<sid;k++){
for(kay=0;kay<100;kay++){
if(calc_first[k][kay] == '!'){
break;
}
else if(calc_first[k][kay] == '#'){
int fz = 1;
while(calc_follow[k][fz] != '!'){
char xz = production[k][0];
int cz=0;
while(table[cz][0] != xz){
cz = cz + 1;
}
int vz=0;
while(ter[vz] != calc_follow[k][fz]){
vz = vz + 1;
}
table[k][vz+1] = '#';
fz++;
}
break;
}
}
}
for(ap = 0; ap < land ; ap++){
printf("\t\t\t %c\t|\t",table[ap][0]);
for(kay = 1; kay < (sid + 1) ; kay++){
if(table[ap][kay] == '!')
printf("\t\t");
else if(table[ap][kay] == '#')
printf("%c=#\t\t",table[ap][0]);
else{
int mum = (int)(table[ap][kay]);
mum -= 65;
printf("%s\t\t",production[mum]);
}
}
printf("\n");
printf("\t\t\t----------------------------------------------------------------------------
-----------------------------------------");
printf("\n");
}
int j;
printf("\n\nPlease enter the desired INPUT STRING = ");
char input[100];
scanf("%s%c",input,&ch);
printf("\n\t\t\t\t\t================================================
===========================\n");
printf("\t\t\t\t\t\tStack\t\t\tInput\t\t\tAction");
printf("\n\t\t\t\t\t================================================
===========================\n");
int i_ptr = 0,s_ptr = 1;
char stack[100];
stack[0] = '$';
stack[1] = table[0][0];
while(s_ptr != -1){
printf("\t\t\t\t\t\t");
int vamp = 0;
for(vamp=0;vamp<=s_ptr;vamp++){
printf("%c",stack[vamp]);
}
printf("\t\t\t");
vamp = i_ptr;
while(input[vamp] != '\0'){
printf("%c",input[vamp]);
vamp++;
}
printf("\t\t\t");
char her = input[i_ptr];
char him = stack[s_ptr];
s_ptr--;
if(!isupper(him)){
if(her == him){
i_ptr++;
printf("POP ACTION\n");
}
else{
printf("\nString Not Accepted by LL(1) Parser !!\n");
break;
}
}
else{
for(i=0;i<sid;i++){
if(ter[i] == her)
break;
}
char produ[100];
for(j=0;j<land;j++){
if(him == table[j][0]){
if (table[j][i+1] == '#'){
printf("%c=#\n",table[j][0]);
produ[0] = '#';
produ[1] = '\0';
}
else if(table[j][i+1] != '!'){
int mum = (int)(table[j][i+1]);
mum -= 65;
strcpy(produ,production[mum]);
printf("%s\n",produ);
}
else{
printf("\nString Not Accepted by LL(1)
Parser !!\n");
break;
}
}
}
int le = strlen(produ);
le = le - 1;
if(le == 0){
continue;
}
for(j=le;j>=2;j--){
s_ptr++;
stack[s_ptr] = produ[j];
}
}
}
printf("\n\t\t\t===================================================
==================================================================
==\n");
if (input[i_ptr] == '\0'){
printf("\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN ACCEPTED !!\n");
}
else
printf("\n\t\t\t\t\t\t\t\tYOUR STRING HAS BEEN REJECTED !!\n");
printf("\t\t\t=====================================================
==================================================================
\n");
}

void follow(char c)
{
int i ,j;
if(production[0][0]==c){
f[m++]='$';
}
for(i=0;i<10;i++)
{
for(j=2;j<10;j++)
{
if(production[i][j]==c)
{
if(production[i][j+1]!='\0'){
followfirst(production[i][j+1],i,(j+2));
}
if(production[i][j+1]=='\0'&&c!=production[i][0]){
follow(production[i][0]);
}
}
}
}
}

void findfirst(char c ,int q1 , int q2)


{
int j;
if(!(isupper(c))){
first[n++]=c;
}
for(j=0;j<count;j++)
{
if(production[j][0]==c)
{
if(production[j][2]=='#'){
if(production[q1][q2] == '\0')
first[n++]='#';
else if(production[q1][q2] != '\0' && (q1 != 0 || q2 !=
0))
{
findfirst(production[q1][q2], q1, (q2+1));
}
else
first[n++]='#';
}
else if(!isupper(production[j][2])){
first[n++]=production[j][2];
}
else {
findfirst(production[j][2], j, 3);
}}}}

void followfirst(char c, int c1 , int c2)


{
int k;
if(!(isupper(c)))
f[m++]=c;
else{
int i=0,j=1;
for(i=0;i<count;i++) {
if(calc_first[i][0] == c)
break; }
while(calc_first[i][j] != '!') {
if(calc_first[i][j] != '#'){
f[m++] = calc_first[i][j];}
else{
if(production[c1][c2] == '\0'){
follow(production[c1][0]);}
else{
followfirst(production[c1][c2],c1,c2+1);}}
j++;
}}}

Output:
11. Aim: Write a program to find parsing table of the given productions.

Program:
#include<conio.h>
#include<iostream.h>
#include<string.h>

struct grammer{
char p[20];
char prod[20];
}g[10];

void main()
{
int i,stpos,j,k,l,m,o,p,f,r;
int np,tspos,cr;

cout<<"\nEnter Number of productions:";


cin>>np;

char sc,ts[10];

cout<<"\nEnter productions:\n";
for(i=0;i<np;i++)
{
cin>>ts;
strncpy(g[i].p,ts,1);
strcpy(g[i].prod,&ts[3]);
}

char ip[10];

cout<<"\nEnter Input:";
cin>>ip;

int lip=strlen(ip);

char stack[10];

stpos=0;
i=0;

//moving input
sc=ip[i];
stack[stpos]=sc;
i++;stpos++;

cout<<"\n\nStack\tInput\tAction";
do
{
r=1;
while(r!=0)
{
cout<<"\n";
for(p=0;p<stpos;p++)
{
cout<<stack[p];
}
cout<<"\t";
for(p=i;p<lip;p++)
{
cout<<ip[p];
}

if(r==2)
{
cout<<"\tReduced";
}
else
{
cout<<"\tShifted";
}
r=0;

//try reducing
getch();
for(k=0;k<stpos;k++)
{
f=0;

for(l=0;l<10;l++)
{
ts[l]='\0';
}

tspos=0;
for(l=k;l<stpos;l++) //removing first caharcter
{
ts[tspos]=stack[l];
tspos++;
}

//now compare each possibility with production


for(m=0;m<np;m++)
{
cr = strcmp(ts,g[m].prod);

//if cr is zero then match is found


if(cr==0)
{
for(l=k;l<10;l++) //removing matched part from stack
{
stack[l]='\0';
stpos--;
}

stpos=k;

//concatinate the string


strcat(stack,g[m].p);
stpos++;
r=2;
}
}
}
}

//moving input
sc=ip[i];
stack[stpos]=sc;
i++;stpos++;

}while(strlen(stack)!=1 && stpos!=lip);

if(strlen(stack)==1)
{
cout<<"\n String Accepted";
}

getch();
}
Output:

You might also like