You are on page 1of 6

WEEK 2. a.

Write a C program to identify whether a given line is a comment or not


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

int main()
{
char line[100]; // input line
int flag = 0; // comment flag
int i; // loop index
int len; // length of the line

printf("Enter a line: ");


fgets(line, 100, stdin); // read the line

len = strlen(line); // get the length of the line


for (i = 0; i < len - 1; i++) // loop through each character
{
if (line[i] == '/') // if the current character is /
{
if (line[i + 1] == '/') // if the next character is also /
{
flag = 1; // set the flag to 1
break; // break the loop
}
else if (line[i + 1] == '*') // if the next character is *
{
flag = 2; // set the flag to 2
i++; // increment the index
}
}
else if (line[i] == '*' && flag == 2)
{
if (line[i + 1] == '/') // if the next character is /
{
flag = 3; // set the flag to 3
break; // break the loop
}
}
}

// print the result based on the flag


if (flag == 1)
printf("The line is a single-line comment.\n");
else if (flag == 3)
printf("The line is a multi-line comment.\n");
else
printf("The line is not a comment.\n");

return 0;
}
WEEK 2 b.Write a C program to test whether a given identifier is valid or not.:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// A function to check if a string is a keyword


bool isKeyword(char *str)
{
char *keywords[] =
{"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"
};

int n = 32; // The number of keywords in C

for (int i = 0; i < n; i++)


{
if (strcmp(str, keywords[i]) == 0)
{
return true; // The string is a keyword
}
}

return false; // The string is not a keyword

bool isValidIdentifier(char *str)


{
// Check the first character
if (!(str[0] == '_' || (str[0] >= 'a' && str[0] <= 'z') || (str[0] >= 'A'
&& str[0] <= 'Z')))
{
return false; // The first character is not valid

// Loop through the remaining characters


for (int i = 1; str[i] != '\0'; i++)
{
// Check the current character
if (!(str[i] == '_' || (str[i] >= 'a' && str[i] <= 'z')
|| (str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0'
&& str[i] <= '9')))
{

return false; // The current character is not valid


}
}
// Check if the string is a keyword
if (isKeyword(str))
{
// The string is a keyword
return false;
}

// The string is a valid identifier


return true;
}

int main()
{
char str[100]; // The input string

printf("Enter an identifier: ");


scanf("%s", str); // Read the identifier

// Check if the identifier is valid or not


if (isValidIdentifier(str))
{
printf("The identifier is valid.\n");
}
else
{
printf("The identifier is not valid.\n");
}

return 0;
}
I can help you with writing a C program to simulate lexical analyzer for validating

operators. 😊

A lexical analyzer is a program that scans the input source code and converts it into
a sequence of tokens. A token is a meaningful unit of information in the language,
such as a keyword, an identifier, an operator, or a punctuation symbol. A lexical
analyzer can be implemented using a finite automaton, which is a machine that can
recognize patterns of characters in the input.

3.To write a C program to simulate lexical analyzer for validating operators, you
need to follow these steps:

1. Define the tokens and their patterns using regular expressions. For example,
a token for an operator might be defined as one of the following symbols: +,
-, *, /, %, =, <, >, !, &, |.
2. Construct a finite automaton that corresponds to the regular expressions.
You can use a tool such as Lex or Flex to generate a finite automaton from
the regular expressions, or you can manually construct a non-deterministic
finite automaton (NFA) and then convert it to a deterministic finite
automaton (DFA) using the subset construction algorithm.
3. Implement the finite automaton in C language. You can use a table-driven
approach, where you store the transition table and the final states of the
DFA in an array or a data structure, and then use a loop to read the input and
move from one state to another according to the table. Alternatively, you
can use a direct-coded approach, where you write the code for each state and
the transitions as a series of if-else or switch-case statements.
4. Add the actions to be performed when a token is recognized. For example,
you might want to print the token and its lexeme (the actual string matched
by the pattern) to the output, or store the token and its lexeme in a data
structure, or pass the token to the next phase of the compiler.

Here is an example of a C program that implements this algorithm:


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

// Define the token types


#define OPERATOR 1
#define OTHER 2

// Define the DFA states


#define START 0
#define OP 1
#define ERROR -1

// Define the transition table


int table[2][128];

// Initialize the transition table


void init_table()
{
// Fill the table with error state
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 128; j++)
{
table[i][j] = ERROR;
}
}

// Fill the table with valid transitions


table[START]['+'] = OP;
table[START]['-'] = OP;
table[START]['*'] = OP;
table[START]['/'] = OP;
table[START]['%'] = OP;
table[START]['='] = OP;
table[START]['<'] = OP;
table[START]['>'] = OP;
table[START]['!'] = OP;
table[START]['&'] = OP;
table[START]['|'] = OP;
}

// Get the next state from the current state and input character
int get_next_state(int state, char input)
{
return table[state][input];
}

// Get the token type from the final state


int get_token_type(int state)
{
if (state == OP)
{
return OPERATOR;
}
else
{
return OTHER;
}
}

// Simulate the lexical analyzer


void simulate(char *input)
{
int len = strlen(input); // Get the length of the input
int i = 0; // Loop index
int state = START; // Current state
int token_type; // Token type
char lexeme[100]; // Lexeme
int lexeme_index = 0; // Lexeme index
while (i < len) // Loop through the input
{
state = get_next_state(state, input[i]); // Get the next state
if (state == ERROR) // If the state is error
{
token_type = get_token_type(state); // Get the token type
lexeme[lexeme_index] = '\0'; // Terminate the lexeme
if (token_type == OPERATOR) // If the token type is operator
{
printf("Operator: %s\n", lexeme); // Print the operator
}
state = START; // Reset the state
lexeme_index = 0; // Reset the lexeme index
}
else // If the state is not error
{
lexeme[lexeme_index++] = input[i]; // Append the input
character to the lexeme
i++; // Increment the loop index
}
}

// Process the last token


token_type = get_token_type(state); // Get the token type
lexeme[lexeme_index] = '\0'; // Terminate the lexeme
if (token_type == OPERATOR) // If the token type is operator
{
printf("Operator: %s\n", lexeme); // Print the operator
}
}

int main()
{
char input[100]; // Input string
printf("Enter the input: ");
scanf("%s", input); // Read the input
init_table(); // Initialize the transition table
simulate(input); // Simulate the lexical analyzer
return 0;
}

I hope this helps you with your task. If you have any questions or feedback, please

let me know. 😊

You might also like