Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

LAB - 2

Kumar Setu (2K19/IT/068)

EXPERIMENT 2
Write a program for the lexical analysis of the code snippet:
if (x>30)
Code:

1. #include <bits/stdc++.h>
2. using namespace std;
3.  
4. string token_function_1(string input, string t1){
5. if(t1=="if"){
6. for(int i=0;i<input.length()-1;i++){
7. if(input[i]=='i' && input[i+1]=='f'){
8. return "<if>";
9. }
10. }
11. return "<no if token>";
12. }
13. return "no if token";
14. }
15. string brackets(string input, string temp){
16. int i=0;
17. int n=input.length();
18. if(temp=="("){
19. i=0;
20. while(i<n){
21. if(input[i]=='('){
22. int j=i+1;
23. while(j<n){
24. if(input[j]==')') return "<PAR,OPEN>";
25. j++;
26. }
27. return "logical error in parenthesis";
28. }
29. i++;
30. }
31. }
32. else if(temp==")"){
33. i=n-1;
34. while(i>=0){
35. if(input[i]==')'){
36. int j=i-1;
37. while(j>=0){
38. if(input[j]=='(') return "<PAR,CLOSE>";
39. j--;
40. }
41. return "logical error in brackets";
42. }
43. i--;
44. }
45. }
46. return "no PAR";
47. }
48. string space(string input){
49. for(int i=0;i<input.length();i++){
50. if(input[i]==' ') return "<>";
51. }
52. return "no space token";
53. }
54. string id(string inp, string t){
55. if(t=="x"){
56. for(int i=0;i<inp.length();i++){
57. if(inp[i]=='x') return "<id,1>";
58. }
59. return "no id";
60. }
61. return "no id";
62. }
63. string sign(string inp, string tok){
64. int n = inp.length();
65. if(tok==">"){
66. for(int i=0;i<inp.length();i++){
67. if(inp[i]=='>') return "<relop,GT>";
68. }
69. return "no relop";
70. }
71. return "no relop";
72. }
73. string numb(string inp, string tok){
74. int n = inp.length();
75. string temp;
76. for(int i=0;i<n;i++){
77. if(inp[i]>='0' && inp[i]<='9'){
78. int j=i;
79. while(j<n && (inp[j]>='0' && inp[j]<='9')){
80. temp+=inp[j];
81. j++;
82. }
83. if(temp==tok) return "<"+temp+">";
84. return "no matching number";
85. }
86. }
87. return "no number";
88. }
89. int main(){
90. string input, t1,t2,t3,t4,t5,t6,t7;
91. getline(cin, input);
92. cout<<"Entered input is: "<<input<<endl;
93. cin>>t1;
94. cout<<"token 1 is: "<<t1<<endl;
95. cin>>t2;
96. cout<<"token 2 is: "<<t2<<endl;
97. cin>>t3;
98. cout<<"token 3 is: "<<t3<<endl;
99. cin>>t4;
100. cout<<"token 4 is: "<<t4<<endl;
101. cin>>t5;
102. cout<<"token 5 is: "<<t5<<endl;
103. cin>>t6;
104. cout<<"token 5 is: "<<t6<<endl;
105. cin>>t7;
106. cout<<"token 7 is: "<<t7<<endl;
107.  
108. cout<<token_function_1(input, t1)<<endl;
109. cout<<brackets(input,t2)<<endl;
110. cout<<space(input)<<endl;
111. cout<<id(input, t4)<<endl;
112. cout<<sign(input, t5)<<endl;
113. cout<<numb(input, t6)<<endl;
114. cout<<brackets(input,t7)<<endl;
115. return 0;
116. }
117.  
Output:

You might also like