Microsoft Word - Lab - Compiler
Microsoft Word - Lab - Compiler
Design a lexical analyzer for given language and the lexical analyzer should ignore
redundant spaces, tabs and new lines. It should also ignore comments. Although the
syntax specification states that identifiers can be arbitrarily long, you may restrict the
length to some reasonable value. Simulate the same in C language.
Source code:
#include<bits/stdc++.h>
using namespace std;
int main(){
ifstream in("in.c");
if(!in){
cout<<"File cannot be opened";
return 1;
}
char ch;
while(in.get(ch)){
if(ch == '>'){
cout << ch << "\n";
ch = in.get();
if(ch == ' ' || ch == '\t' || ch == '\n')
goto nl;
else
cout << ch;
}
else if(ch == '('){
cout << ch;
ch = in.get();
while(ch != ')'){
cout << ch;
ch = in.get();
}
cout << ch;
ch = in.get();
if(ch == ' '){
ch = in.get();
while(ch == ' ' || ch == '\t' || ch == '\n'){
ch = in.get();
continue;
}
goto x;
}
else
x: ch == ';' ? cout << ";\n" : cout << "\n";
}
else if(ch == ' ' || ch == '\t' || ch == '\n'){
if(ch == ' '){
cout << ch;
nl:
ch = in.get();
while(ch == ' ' || ch == '\t' || ch == '\n'){
ch=in.get();
continue;
}
cout << ch;
}
}
else if(ch == ';'){
cout << ch << "\n";
ch = in.get();
if(ch == ' ' || ch == '\t' || ch == '\n')
goto nl;
else
cout<<ch;
}
else
cout<<ch;
}
in.close();
}
in.c :
#include<stdio.h>
void main()
int a,b;
printf("Hello World");
for(i=0;i<5;i++)
printf("i");
}
Practical 2
Write a C program to identify whether a given line is a comment or not.
Source code:
int main(){
int arr[100];
char input[1000];
cout << "Enter your string ctrl + z to terminate \n";
scanf("%[^z]", input);
Output:
Enter your string ctrl + z to terminate
//hi there /*this is comment program*/
/*this is //another comment */
^Z
Number of lines in above lines are 2
Number of comments in above lines are 2 and they are in following lines
1
2
Practical 3
Write a C program to test whether a given identifier is valid or not.
Source code:
int main(){
char keyword[32][15] = {"int", "float", "char", "bool", "void",
"double", "long", "case", "using", "sizeof",
"const", "enum", "extern", "namespace", "for", "while", "do",
"switch", "if", "else", "return", "default",
"typedef", "short", "union", "goto", "volatile", "unsigned",
"static", "register", "struct", "break"};
char input[100];
cout << "Enter a Identifier & press enter: ";
scanf("%[^\n]", input);
return 0;
}