Skip to main content

Posts

Program 4: Factorial Calculation

  **Program 4: Factorial Calculation** ```assembly .model small .stack 100h .data     num dw 5     result dw 1 .code     main proc         mov cx, num          ; Load 'num' into CX         mov ax, 1            ; Initialize 'result' to 1     loop_start:         mul cx               ; Multiply AX by CX (result *= num)         loop loop_start      ; Decrement CX and loop if not zero         mov result, ax       ; Store result in 'result'                  mov ah, 4Ch          ; Exit program...

Program 3: Find the Maximum of Two Numbers

  **Program 3: Find the Maximum of Two Numbers** ```assembly .model small .stack 100h .data     num1 dw 5     num2 dw 7     result dw ? .code     main proc         mov ax, num1        ; Load first number into AX         cmp ax, num2        ; Compare with second number         jge greater         ; Jump to greater if AX >= num2                  mov ax, num2        ; Load second number into AX         jmp end_prog              greater:         mov ax, num1     end_prog: ...

Program 2: Sum of Two Numbers

     ** Program 2: Sum of Two Numbers ** ```assembly .model small .stack 100h .data     num1 dw 5     num2 dw 7     result dw ? .code     main proc         mov ax, num1        ; Load first number into AX         add ax, num2        ; Add second number to AX         mov result, ax      ; Store result in 'result'                  mov ah, 4Ch          ; Exit program         int 21h     main endp end main ``` Explanation: 1. `.model small` and `.stack 100h`: Memory model and stack size definitions. 2. `.data` section: Declares the data segment.    - `num1 dw 5`: Defines a word-sized variable named "num1" with value 5.    - `num2 dw 7`: Defines a word-sized variable named "num2" with value 7.    -...

Program 1: Hello World

 **Program 1: Hello World** ```assembly .model small .stack 100h .data     message db 'Hello, World!', '$' .code     main proc         mov ah, 09h          ; DOS function to print string         lea dx, message      ; Load effective address of message         int 21h              ; Call DOS interrupt         mov ah, 4Ch          ; Exit program         int 21h     main endp end main ``` Explanation: 1. `.model small` and `.stack 100h`: Memory model and stack size definitions. 2. `.data` section: Declares the data segment.    - `message db 'Hello, World!', '$'`: Defines a null-terminated string. 3. `.code` section: Contains the main code.    - `mov ah, 09h`: Load DOS function code for printing a string.    - `lea dx, message`: L...

18. Implement Intermediate code generation for simple expressions.

Creating a complete implementation of intermediate code generation for simple expressions would be quite extensive, but I can provide you with a simple example along with explanations for each line of code. In this example, we'll generate three-address code for arithmetic expressions involving addition and subtraction. ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int tempCount = 0; // Function to generate a new temporary variable char* newTemp() {     char* temp = (char*)malloc(4);     sprintf(temp, "t%d", tempCount);     tempCount++;     return temp; } int main() {     char expr[50];     printf("Enter an arithmetic expression: ");     scanf("%[^\n]", expr);     char* result = newTemp();     printf("%s = %s\n", result, expr);     return 0; } ``` Explanation of the code: 1. `#include <stdio.h>`: Include the standard I/O library for input/output fu...

17. Write a program to perform constant propagation.

Sure, I can provide you with a basic example of a constant propagation program along with explanations for each line. Please note that this example is simplified and might not cover all possible cases of constant propagation. ```c #include <stdio.h> #include <stdbool.h> // Structure to represent an assignment statement struct Assignment {     char variable;     int value;     bool isConstant; }; int main() {     // Example assignments (variable, value, isConstant)     struct Assignment assignments[] = {         {'a', 10, true},         {'b', 20, true},         {'c', 0, true},         {'d', 30, false},         {'e', 0, false}     };     int numAssignments = sizeof(assignments) / sizeof(assignments[0]);     // Perform constant propagation     for (int i = 0; i < numAssignments; i++) { ...

16. Construct a Shift Reduce Parser for a given language.

Constructing a Shift-Reduce Parser involves implementing a parsing algorithm that shifts tokens onto a stack and then reduces them using production rules. Since a full implementation can be quite extensive, I'll provide you with a basic example in Python and explain each line of code. Note that this example will use a simple grammar for illustration purposes. **Example Grammar**: ``` E -> E + T | T T -> T * F | F F -> ( E ) | id ``` **Python Shift-Reduce Parser Example**: ```python # Input string to be parsed input_string = "id + id * id" # Define grammar rules as a dictionary grammar = {     "E": [["E", "+", "T"], ["T"]],     "T": [["T", "*", "F"], ["F"]],     "F": [["(", "E", ")"], ["id"]] } # Define terminals and non-terminals terminals = set(["+", "*", "(", ")", "id...

15.Design and implement a recursive descent parser for a given grammar.

Designing and implementing a recursive descent parser involves breaking down the grammar into recursive functions that correspond to its production rules. Each function handles a non-terminal symbol in the grammar and recursively calls other functions to parse the input based on the grammar rules. Here's an example of a simple recursive descent parser for a grammar that recognizes arithmetic expressions with + and * operators and parentheses: ```c #include <stdio.h> #include <ctype.h> // Global variables char input[100]; int position = 0; // Function to consume a character from the input char getNextChar() {     return input[position++]; } // Function to parse and evaluate a factor int factor(); // Function to parse and evaluate a term int term(); // Function to parse and evaluate an expression int expression(); int main() {     printf("Enter an arithmetic expression: ");     scanf("%s", input);     int result = expression();   ...

14. Write a program to find the First and Follow of any given grammar.

Sure, I can provide you with a simple example of a program to find the First and Follow sets of a given grammar using Python. I'll explain each line of the code as well. ```python # Define the grammar rules grammar = {     'E': ['T E\''],     'E\'': ['+ T E\'', 'epsilon'],     'T': ['F T\''],     'T\'': ['* F T\'', 'epsilon'],     'F': ['( E )', 'id'] } # Initialize First and Follow sets first_sets = {} follow_sets = {} # Initialize terminals and non-terminals terminals = set(['+', '*', '(', ')', 'id']) non_terminals = set(grammar.keys()) # Initialize First sets with empty sets for symbol in non_terminals:     first_sets[symbol] = set() # Helper function to calculate First set of a symbol def calculate_first(symbol):     if symbol in terminals:         return set([symbol])     first = set()...

13. Write a program to minimize any given DFA.

Sure, I can help you write and explain a program to minimize a given DFA (Deterministic Finite Automaton). Before we begin, please note that this is a complex topic and explaining every line in detail might result in a lengthy explanation. However, I'll provide a code example and explain the key parts of the algorithm used for DFA minimization. Here's a Python program to minimize a given DFA: ```python def minimize_dfa(dfa):     # Partition the states into accepting and non-accepting sets     accepting_states = set()     non_accepting_states = set()     for state in dfa['states']:         if state in dfa['accepting_states']:             accepting_states.add(state)         else:             non_accepting_states.add(state)     # Initialize the partition     partition = [accepting_states, non_accepting_states]     new_part...

12. Write a program to convert NFA to DFA.

Converting a Non-Deterministic Finite Automaton (NFA) to a Deterministic Finite Automaton (DFA) involves creating a new DFA where each state corresponds to a set of NFA states reachable under certain conditions. Below is a simple Python program to perform this conversion. I'll explain each line of code: ```python from collections import defaultdict def epsilon_closure(states, transitions, epsilon):     closure = set(states)     stack = list(states)          while stack:         state = stack.pop()         for next_state in transitions[state].get(epsilon, []):             if next_state not in closure:                 closure.add(next_state)                 stack.append(next_state)          return closure def nfa_to_dfa(nfa_states, nfa_transitions, alphabet, start_state, n...