Laboratory Manual Software Design Laboratory Third Year - Information Technology Teaching Scheme Examination Scheme Theory : 01 Hrs/Week Term Work: 50 Marks Practical : 04 Hrs/Week Practical : 50 Marks Oral : —— Prepared By Prof. Shridevi A. Swami Department of Information Technology Vidya Pratishthan’s College of Engineering Baramati – 413133, Dist- Pune (M.S.) INDIA December 2012 Table of Contents PART-A : System Software 1 1 Two Pass Assembler 1.1 Problem Statement . . . . . . . . . . . . . . 1.2 Pre Lab . . . . . . . . . . . . . . . . . . . . 1.3 Theory . . . . . . . . . . . . . . . . . . . . . 1.3.1 Assembler: . . . . . . . . . . . . . . 1.3.2 Design of Two pass assembler . . . . 1.3.3 Required Data structures . . . . . . 1.3.4 Representation of Intermediate Code 1.3.5 Representation of Machine Code . . 1.4 Sample Input/Output . . . . . . . . . . . . 1.5 Conclusion . . . . . . . . . . . . . . . . . . 1.6 Post Lab . . . . . . . . . . . . . . . . . . . . 1.7 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 2 2 2 3 4 5 6 7 9 9 9 2 Two Pass Macro Processor 2.1 Problem Statement . . . . . . . . . . . . . . 2.2 Pre Lab . . . . . . . . . . . . . . . . . . . . 2.3 Theory . . . . . . . . . . . . . . . . . . . . . 2.3.1 Macro . . . . . . . . . . . . . . . . . 2.3.2 Macro definition part . . . . . . . . 2.3.3 Macro Call and Expansion . . . . . 2.3.4 Design of Two pass macro processor 2.4 Procedure . . . . . . . . . . . . . . . . . . . 2.5 Sample Input/Output . . . . . . . . . . . . 2.6 Conclusion . . . . . . . . . . . . . . . . . . 2.7 Post Lab . . . . . . . . . . . . . . . . . . . . 2.8 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 11 11 11 11 12 12 12 13 14 16 16 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and Lastpos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 17 17 17 17 18 19 19 20 20 22 3 RE 3.1 3.2 3.3 to DFA Problem Statement . . . . . . . . Pre Lab . . . . . . . . . . . . . . Theory . . . . . . . . . . . . . . . 3.3.1 Overview . . . . . . . . . 3.3.2 Data Structures . . . . . . 3.3.3 Rules for Computations of 3.3.4 Computation of Followpos 3.4 Procedure . . . . . . . . . . . . . 3.5 Sample Input/Output . . . . . . 3.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Nullable , . . . . . . . . . . . . . . . . . . . . . . . . i . . . . . . . . . . . . . . . . . . . . . . . . . Firstpos . . . . . . . . . . . . . . . . . . . . TABLE OF CONTENTS 3.7 3.8 TABLE OF CONTENTS Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Lexical Analyzer 4.1 Problem Statement . . . . . . . . . . . 4.2 Pre Lab . . . . . . . . . . . . . . . . . 4.3 Theory . . . . . . . . . . . . . . . . . . 4.3.1 Tasks of Lexical Analysis Phase 4.3.2 Databases . . . . . . . . . . . . 4.3.3 Algorithm . . . . . . . . . . . . 4.4 Sample Input/Output . . . . . . . . . 4.5 Conclusion . . . . . . . . . . . . . . . 4.6 Post Lab . . . . . . . . . . . . . . . . . 4.7 Viva Questions . . . . . . . . . . . . . 22 22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 23 23 23 23 24 25 25 27 27 27 5 Recursive Descent parser 5.1 Problem Statement . . . . . . . . . . . . 5.2 Pre Lab . . . . . . . . . . . . . . . . . . 5.3 Theory . . . . . . . . . . . . . . . . . . . 5.3.1 Parsing . . . . . . . . . . . . . . 5.3.2 Types of parser . . . . . . . . . . 5.3.3 Recursive descent parser . . . . . 5.3.4 Predictive parser . . . . . . . . . 5.3.5 Predictive Parsing-LL (1) Parsers 5.4 Conclusion . . . . . . . . . . . . . . . . 5.5 Post Lab . . . . . . . . . . . . . . . . . . 5.6 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 29 29 29 29 29 30 31 31 32 33 33 6 Calculator using LEX and YACC 6.1 Problem Statement . . . . . . . . . . . . 6.2 Pre Lab . . . . . . . . . . . . . . . . . . 6.3 Hardware and Software Requirement . . 6.4 Theory . . . . . . . . . . . . . . . . . . . 6.4.1 Introduction . . . . . . . . . . . 6.4.2 Lex Specification . . . . . . . . . 6.4.3 Parser Generators . . . . . . . . 6.4.4 Communication between Lex and 6.5 Conclusion . . . . . . . . . . . . . . . . 6.6 Post Lab . . . . . . . . . . . . . . . . . . 6.7 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . YACC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 34 34 34 34 34 35 35 37 37 37 37 7 Screen Editor 7.1 Problem Statement . . . . . . . . . 7.2 Pre Lab . . . . . . . . . . . . . . . 7.3 Theory . . . . . . . . . . . . . . . . 7.3.1 Editor and Types of Editor 7.3.2 Design of an Editor . . . . 7.4 Procedure . . . . . . . . . . . . . . 7.4.1 Algorithm . . . . . . . . . . 7.4.2 Function :dispmenu() . . . 7.4.3 Function :dispfile() . . . . . 7.4.4 Function :disphelp() . . . . 7.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 38 38 38 38 39 40 40 41 41 43 43 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TABLE OF CONTENTS 7.6 7.7 TABLE OF CONTENTS Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Dyanamic Link Library 8.1 Problem Statement . . . . . . . . . . . . . . . . . . . 8.2 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Hardware and Software Requirement . . . . . . . . . 8.4 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4.1 What is Static linking and Dynamic linking? 8.4.2 Example . . . . . . . . . . . . . . . . . . . . 8.4.3 Required Files . . . . . . . . . . . . . . . . . 8.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . 8.6 Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . 8.7 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . PART-B : Design and Analysis of Algorithms 9 Tower of Hanoi 9.1 Problem Statement . . . . 9.2 Pre Lab . . . . . . . . . . 9.3 Theory . . . . . . . . . . . 9.3.1 Introduction . . . 9.3.2 Recursive solution 9.4 Procedure . . . . . . . . . 9.5 Conclusion . . . . . . . . 9.6 Post Lab . . . . . . . . . . 9.7 Viva Questions . . . . . . 43 43 44 44 44 44 44 44 45 47 48 48 48 49 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 50 50 50 50 51 52 52 52 52 10 Kruskal’s algorithm 10.1 Problem Statement . . . . . . . . . . . . . . . . . . . . . . 10.2 Pre Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3 Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3.1 Introduction to greedy algorithm . . . . . . . . . . 10.3.2 Kruskal’s algorithm for finding Minimum Spanning 10.4 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.5 Sample Input/Output . . . . . . . . . . . . . . . . . . . . 10.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . 10.7 Post Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.8 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 53 53 53 53 54 54 54 55 55 55 11 8 Queen Problem 11.1 Problem Statement . . . . . . 11.2 Pre Lab . . . . . . . . . . . . 11.3 Theory . . . . . . . . . . . . . 11.3.1 Backtracking . . . . . 11.3.2 The 8-Queen Problem 11.3.3 Basic idea of solution 11.4 Procedure . . . . . . . . . . . 11.5 Conclusion . . . . . . . . . . 11.6 Post Lab . . . . . . . . . . . . 11.7 Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 56 56 56 56 56 57 57 58 58 59 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 iii TABLE OF CONTENTS PART-A System Software Lab Manual - Software Design Laboratory 1 VPCOE, Baramati Assignment 1 Two Pass Assembler 1.1 Problem Statement Implementation of Two Pass assembler in C with hypothetical Instruction set. Instruction set should include all types of assembly language statements such as Imperative, Declarative and Assembler Directive. While designing stress should be given on • How efficiently Pass I generates Intermediate code. • Pass II generates machine code with the help of Intermediate code given by pass I. 1.2 Pre Lab • Concept of assembly language and its processing. • Concept of two pass assembler. 1.3 1.3.1 Theory Assembler: It creates object code by translating assembly instruction mnemonics into opcodes, and by resolving symbolic names for memory locations and other entities. 2 Two Pass Assembler Figure 1.1: Concept of Assembler There are two types of assemblers based on how many passes through the source are needed to produce the executable program. 1. One-pass assemblers go through the source code once and assume that all symbols will be defined before any instruction that references them. 2. Two-pass assemblers create a table with all symbols and their values in the first pass, and then use the table in a second pass to generate code. The assembler must at least be able to determine the length of each instruction on the first pass so that the addresses of symbols can be calculated. 1.3.2 Design of Two pass assembler Task performed by the passes of a two pass assembler are as follows: • Pass I 1. Separate the symbol, mnemonic opcode and operand fields. 2. Build the symbol table. 3. Perform LC processing. 4. Construct intermediate representation. • Pass II 1. Synthesize the target program. As shown in figure below the Pass I perform analysis of the source program and synthesis of the intermediate representation while Pass II processes the intermediate representation to synthesize the target program. Lab Manual - Software Design Laboratory 3 VPCOE, Baramati Two Pass Assembler Figure 1.2: Overview of two pass assembly 1.3.3 Required Data structures 1. Opcode Table: Assembler need not to enter information in this table. This table with information is available with the assembler. The assembler does not enter information in this table but uses this data structure • To determine valid imperative statement. • Find length of instruction • Find corresponding machine Opcode. Fields of Opcode Table: (a) Opcode (b) Machine code (c) Type of Opcode (d) Length of Opcode 2. Register Table: This table stores the information about registers supported by system. Fields of Register Table: Lab Manual - Software Design Laboratory 4 VPCOE, Baramati Two Pass Assembler (a) Register name (b) Machine constant 3. Symbol Table: This table is used to record information about symbols in program. Symbols can be • Label appearing on any statement • Constant declared by ’DC’ statement • Storage variable declared by ’DS’ statement This table is created by Pass-I and used by Pass-II of 2-pass assembler. Fields of Symbol Table: (a) Symbol no (b) Symbol name (c) Symbol address (d) Symbol length 4. Literal Table: This table is used to store the information about literals. This table is created by Pass-I and used by Pass-II of 2-pass assembler. Fields of Literal Table: (a) Literal no (b) Literal (c) Literal address 5. Literal Pool Table: This table stores information about literal pools in the assembly program. No of literal pools is always 1 greater than number of LTORG statements in assembly program. This table is created by Pass-I and used by Pass-II of 2-pass assembler. Pool table can be implemented as one dimensional array where index of array indicates literal pool no and POOLTABLE[x] indicates literal number of starting literal in literal pool ’x’ 1.3.4 Representation of Intermediate Code Format of Intermediate Code is as follows: Address Lab Manual - Software Design Laboratory Opcode 5 Operand VPCOE, Baramati Two Pass Assembler 1. Address: Address can be specified or determined by using location counter 2. Opcode: It has two parts: • Type of Opcode i.e. IS, DL, AD • Machine code 3. Operand: It has two parts: • First Operand i.e. Register operand with IC (Machine constant) • Second Operand i.e Symbol operand with IC (S, Symbol no) or Literal Operand with IC (L, Literal no) or Constant Operand with IC (C, Constant value) 1.3.5 Representation of Machine Code Opcode Operand Format of Machine Code is as follows: 1. Opcode: It consists of Machine code of the opcode 2. Operand: It has two parts: • First Operand i.e. Register operand with machine code (Machine constant) • Second Operand i.e Symbol operand with machine code as its address or Literal Operand with machine code as its address or Constant Operand with machine code as its value Lab Manual - Software Design Laboratory 6 VPCOE, Baramati Two Pass Assembler 1.4 Sample Input/Output SAMPLE INPUT FILE START 202 MOVER AREG, =’5’ MOVEM AREG , A LOOP MOVER AREG, A MOVER CREG, B ADD CREG, = ’1’ MOVEM CREG, B SUB CREG,A BC ANY, NEXT LTORG ADD CREG,B BC LE LOOP NEXT SUB AREG, = ’1’ BC LT, BACK STOP ORIGIN 219 MULT CREG, B A DS 1 BACK EQU LOOP B DS 1 END SAMPLE OUTPUT FILE OF INTERMEDIATE CODE 202) 203) 204) 205) 206) 207) 208) 209) 210) 211) 212) 213) 214) 215) 216) 217) 219) 220) 221) 221) 222) (IS,04) (1) (IS,05) (1) (IS,04) (1) (IS,04) (3) (IS,01) (3) (IS,05) (2) (IS,02) (3) (IS,07) (6) (AD, 04) (L,1) (S,1) (S,1) (S,3) (L,2) (S,3) (S,1) (S,4) (IS,01) (3) (S,2) (IS,07) (2) (S,2) (IS,02) (1) (L,3) (IS.07) (1) (S,5) (IS,00) (AD,03) (IS,03) (3) (S,3) (DL,02) (C,1) (AD,02) (DL,02) (C,1) (AD,05) Data Structures Generated: Table 1.1: SYMBOL TABLE Index 1 2 3 4 5 Lab Manual - Software Design Laboratory Symbol A LOOP B NEXT BACK 7 address 220 204 221 214 204 VPCOE, Baramati Two Pass Assembler Table 1.2: LITERAL TABLE Index 1 2 3 Literal =’5’ =’1’ =’1’ address 210 211 222 Table 1.3: LITERAL POOL TABLE Literal Index 1 3 Lab Manual - Software Design Laboratory 8 VPCOE, Baramati Two Pass Assembler SAMPLE INPUT FILE START 202 MOVER AREG, =’5’ MOVEM AREG , A LOOP MOVER AREG, A MOVER CREG, B ADD CREG, = ’1’ MOVEM CREG, B SUB CREG,A BC ANY, NEXT LTORG ADD CREG,B BC LE LOOP NEXT SUB AREG, = ’1’ BC LT, BACK STOP ORIGIN 219 MULT CREG, B A DS 1 BACK EQU LOOP B DS 1 END 1.5 SAMPLE OUTPUT FILE FOR TARGET CODE 202) 04 1 203) 05 1 204) 04 1 205) 04 3 206) 01 3 207) 05 3 208) 03 3 209) 07 6 210) 00 0 00 0 001 01 3 221 213) 07 2 214) 02 1 215) 07 1 216) 00 0 217) 219) 03 3 220) 221) 221) 222) 00 0 210 220 220 221 211 221 220 214 005 204 222 220 000 221 001 Conclusion With the help of implementation of this two pass assembler we demonstrated that forward references can be handled easily in two pass assembler. In First Pass LC processing is done and symbols defined in program are entered into symbol table. The Second Pass synthesizes the target code from Intermediate Representation provied by First Pass and using the address information found in symbol table. 1.6 Post Lab Following objectives are met • To study basic translation process of assembly language to machine language. • To study two pass assembly process. 1.7 Viva Questions 1. Explain what is meant by pass of an assembler. 2. Explain the need for two pass assembler. Lab Manual - Software Design Laboratory 9 VPCOE, Baramati Two Pass Assembler 3. Explain terms such as Forward Reference and backward reference. 4. Explain various types of errors that are handled in two different passes. 5. Explain the need of Intermediate Code generation and the variants used. 6. State various tables used and their significance in the design of two pass Assembler. Lab Manual - Software Design Laboratory 10 VPCOE, Baramati Assignment 2 Two Pass Macro Processor 2.1 Problem Statement Implementation of Macro Processor in C. Following cases to be considered while implementation • Macro without any parameters • Macro with Positional Parameters • Macro with Key word parameters • Macro with positional and keyword parameters. (Conditional expansion, nested macro implementation not expected) 2.2 Pre Lab • Concept of assembly language. • Concept of preprocessing. • Process of two pass macro processor. 2.3 Theory 2.3.1 Macro An assembly language macro facility is to extend the set of operations provided in an assembly language. In order that programmers can repeat identical parts of their program, macro facility can be used. This allows the programmer to define an abbreviation for a part of program and use this abbreviation in the 11 Two Pass Macro Processor program. This abbreviation is treated as macro definition and saved by the macro processor. For all occurrences the abbreviation i.e. macro call, macro processor substitutes the definition. 2.3.2 Macro definition part It consists of 1. Macro Prototype Statement - This declares the name of macro and types of parameters like positional, keyword or mixing of both. 2. Model statement - It is statement from which assembly language statement is generated during macro expansion. 3. Preprocessor Statement - It is used to perform auxiliary function during macro expansion. 2.3.3 Macro Call and Expansion The operation defined by a macro can be used by writing a macro name in the mnemonic field and its operand in the operand field. Appearance of the macro name in the mnemonic field leads to a macro call. Macro call replaces such statements by sequence of statement comprising the macro. This is known as macro expansion. 2.3.4 Design of Two pass macro processor The Macro Preprocessor accepts an assembly program containing macro definitions and calls and translates it into an assembly program which does not contain macro definitions or calls. The program form which is the output given by the Macro Preprocessor can now be handed over to an assembler to obtain the target language form of the program. Figure 2.1: Concept of Macro Preprocessor Lab Manual - Software Design Laboratory 12 VPCOE, Baramati Two Pass Macro Processor Data structures required for macro definition processing: 1. Macro Name Table [MNT]Fields - Index, Name of Macro, MDTP (Macro Definition Table Pointer). 2. Argument List Array Table- [ALA] Fields -Index, Parameter Name 3. Macro Definition Table [MDT]Model Statements present between MACRO and MEND keywords are stored. Fields-Statement no, definition 4. Counters MNTC, ALAC, and MDTC for MNT, ALA and MDT respectively. 2.4 Procedure Pass I 1. Read source program line by line. 2. If read line is MACRO • Identify macro name and make entry in MNT. • Identify macro parameters and prepare ALA. • Store Macro Definition statements in MDT till read line is not MEND. 3. If read line is not MACRO • Write the read line in modified source file. 4. Display MNT, ALA, MDT, modified source file as the output of Pass I. Pass II 1. Read modified source program line by line. 2. If read line is Macro Call • Get the Macro Definition statements from MDT. • Substitute the formal parameters with actual parameters. • Write the statement to the expanded file till MEND is not reached in MDT. 3. If read line is not Macro Call • Write the read line in expanded source file. 4. Display expanded source file as the output of Pass II. Lab Manual - Software Design Laboratory 13 VPCOE, Baramati Two Pass Macro Processor 2.5 Sample Input/Output Sample Input - The assembly language program with macro definitions and macro calls MACRO INCR &MEM-VAL, &INCR-VAL, &REG MOVER &REG, &MEM-VAL ADD MOVEM &REG, &INCR-VAL &REG, &MEM-VAL MEND START MOVER AREG, B ADD AREG, N INCR A, B, AREG MOVEM AREG, N MOVEM BREG, N MOVEM A, N A DS 5 B DS 1 N DS 1 END Sample output Modified source file after Pass I START MOVER AREG, B ADD AREG, N INCR A, B, AREG MOVEM AREG, N MOVEM BREG, N MOVEM A, N A DS 5 B DS 1 N DS 1 END Lab Manual - Software Design Laboratory 14 VPCOE, Baramati Two Pass Macro Processor Data Structures generated by Pass I Table 2.1: Macro Name Table Index 1 Name INCR MDTP 0 Table 2.2: Argument List Array table Index 1 2 3 Formal Argument &MEM-VAL &INCR-VAL &REG Actual Argument A B AREG Table 2.3: Macro Definition table Index 0 1 2 3 4 Statement of the macro INCR &MEM-VAL, &INCR-VAL, &REG MOVER #3,#1 ADD #3,#2 MOVEM #3,#1 MEND Expanded code with no macro definition and macro calls generated by Pass II START MOVER AREG, B ADD AREG, N MOVER AREG, A ADD AREG, B MOVEM AREG, A MOVEM AREG, N MOVEM BREG, N MOVEM A, N A DS 5 B DS 1 N DS 1 END Lab Manual - Software Design Laboratory 15 VPCOE, Baramati Two Pass Macro Processor 2.6 Conclusion With the help of implementation of this two pass macro processor we demonstrated that the macros are used to provide a program generation facility through macro expansion which is lexical expansion or semantic expansion. Lexical expansion implies replacement of formal parameters by corresponding actual parameters. Semantic expansion implies generation of instructions tailored to the requirements of a specific usage. 2.7 Post Lab Following objectives are met • To understand macro facility, features and its use in assembly language programming. • To study how the macro definition is processed and how macro call results in the expansion of code. 2.8 Viva Questions 1. Define the term macro. 2. Distinguish between macro and a subroutine 3. Define and Distinguish between parameters that can be used in macros. 4. State various tables used in processing the macro. 5. Explain the role of stack in nested macros. Lab Manual - Software Design Laboratory 16 VPCOE, Baramati Assignment 3 RE to DFA 3.1 Problem Statement Implementation of program to convert the Regular Expression to DFA in C. 3.2 Pre Lab • TOC knowledge. • Concept of Regular Expression, Deterministic Finite Automata. • Concept of stack, linked list, expression tree. 3.3 Theory 3.3.1 Overview Regular expressions are used to specify regular languages and finite automata are used to recognize the regular languages. e.g. An identifier is a word which begins with an alphabet (capital or small) followed by zero or more letters or digits (0..9). This can be defined by the regular expression (letter) . ( letter | digit)* where letter = A|B|C||Z| a| b |c ||z and digit = 0|1|2|.|9 These regular expressions are then converted to DFA’s in the form of DFA transition table. Lexical analyzer reads a character from a source program and based on the current state and current 17 RE to DFA symbol read, makes a transition to some other state. When it reaches a final state of DFA, it groups the series of characters so far read and outputs the token found. 3.3.2 Data Structures Node Structure for Parse Tree { Leftchild and Rightchild : pointers to the node structure Data: Character Type Pos : Integer Nullable : Integer Type Fistpos and Lastpos : Integer array } Stack: Stack is required to build the tree. This can be implemented either using link list or as an array. Item or data that will be pushed into or popped out from stack is pointer to the node structure of a Parse Tree and not just a single character. Structure for Follow positions { Data: Character Type Pos : Integer Follow : Integer array } Lab Manual - Software Design Laboratory 18 VPCOE, Baramati RE to DFA 3.3.3 Rules for Computations of Nullable , Firstpos and Lastpos 3.3.4 Computation of Followpos Followpos (i) tells us what positions can follow position I in the syntax tree. This can be computed as follows. 1. If n is a ’.’ (cat) Node, with a left child C1 and right child C2 and i is a position in the Lastpos(C1), then all positions in Firstpos(C2) are in Followpos(i) 2. if n is a ’*’ (closure) Node and i is a position in the Lastpos(n), then all positions in Firstpos(n) are Followpos(i) Lab Manual - Software Design Laboratory 19 VPCOE, Baramati RE to DFA 3.4 Procedure 1. Accept the given regular expression with end of character as # 2. Covert the regular expressions to its equivalent postfix form manually. 3. Construct a syntax tree from the postfix expression obtained in step 2. 4. Assign positions to leaf nodes 5. Compute following functions (Rules are mentioned in above section): Nullable, Firstpos, Lastpos, Followpos 6. Construct DFA from Follow Pos (Algorithm for constructing DFA is mentioned below) Algorithm for construction of DFA transition table 1. Initially, the only unmarked state in Dstates is Firstpos(root), where root is the root of a syntax tree. 2. While there is an unmarked state T in Dstates do Begin Mark T For each input symbol a do Begin Let U be the set of positions that are in Followpos (P) for some P in T, such that the symbol at position P is a. If U is not empty and is not in Dstates then add U as an unmarked state to Dstates Dtran [T, a] = U End End 3.5 Sample Input/Output Sample Input: Enter postfix form of the regular expression (r. #) and use dot operator for concatenation and ’|’ for OR and * for closure. For Example (r. #) is: (a| b)*. a .b .b .# then equivalent Postfix Expression is ab|*a.b.b.#. Lab Manual - Software Design Laboratory 20 VPCOE, Baramati RE to DFA Sample output: Post Order Traversal of the tree is ab|*a.b.b.#. Follow Positions: Lab Manual - Software Design Laboratory 21 VPCOE, Baramati RE to DFA DFA: (graphical output is not expected at all): 3.6 Conclusion A recognizer for a language is a program that takes as input a string x and answers ’yes’ if x is a sequence of the language and ’no’ otherwise. We done a program to convert a regular expression into recognizer by constructing a deterministic finite automata. 3.7 Post Lab Following objectives are met • To understand the role of regular expressions and finite automata in applications such as Compilers 3.8 Viva Questions 1. Define regular expression and DFA. 2. Give applications where regular expressions could be used. 3. Explain the significance of firstposition, lastposition and follow position in the algorithm. 4. Any alternate method to convert RE to DFA? If yes compare the methods from space and time complexity point of view. Lab Manual - Software Design Laboratory 22 VPCOE, Baramati Assignment 4 Lexical Analyzer 4.1 Problem Statement Lexical Analyzer for subset of C. 4.2 Pre Lab • Concept of LEX program structure. • Compilation and execution process should be known to student. • Concept of symbol, literal and uniform symbol. 4.3 Theory Lexical analyzer’s main task is to read input characters and produce as output a sequence of tokens that the parser uses for syntax analysis. 4.3.1 Tasks of Lexical Analysis Phase 1. To parse the source program into the basic elements or tokens of the language. 2. To build a literal table and an identifier table. 3. To build an uniform symbol table. 23 Lexical Analyzer 4.3.2 Databases 1. Source Program- Original form of program which appears to the compiler as a string of characters. 2. Terminal Table- A permanent database that has an entry for each terminal symbol (e.g. arithmetic operators, keywords, etc. INDEX SYMBOL INDICATOR (Operator or Break character) 3. Literal Table- Created by lexical analysis to describe all literals used in the source program. There is one entry for each literal. INDEX LITERAL 4. Identifier table- Created by lexical analysis to describe all identifiers used in the source program. There is one entry for each identifier. INDEX IDENTIFIER 5. Uniform Symbol Table (UST)- Created by lexical analysis to represent the program as a string of tokens rather than of individual characters. Lab Manual - Software Design Laboratory 24 VPCOE, Baramati Lexical Analyzer TOKEN 4.3.3 CLASS OF TOKEN INDEX IN THEIR TABLE Algorithm 1. Identify token as lexeme. 2. First check the lexeme in Terminal table. • If present, token is identified as a terminal symbol and entry is made in UST as (’TRM’, index). 3. If token is not terminal symbol, then check it for identifier rules. • If token is classified as ’identifier’, then check in Identifier table to avoid duplicate entry. • If not present in Identifier table, then a new entry is made in Identifier table. • Entry in UST is made as (’IDN’, index). 4. If token is not identifier, then check it for literal rules. • If token is classified as ’literal’, then check in Literal table to avoid duplicate entry. • If not present in Terminal table, then a new entry is made in Literal table. • Entry in UST is made as (’LIT’, index). 4.4 Sample Input/Output Sample Input: if (a<10) i=a+5; Lab Manual - Software Design Laboratory 25 VPCOE, Baramati Lexical Analyzer Sample Output: 1. Terminal Table (TRM) INDEX 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 SYMBOL main void if else while int float char printf scanf ( ) { } ; , + * / < > = INDICATOR (Operator or Break character) O O O O O O O O O O B B B B B B B B B B B B B 2. Identifier Table (IDN) INDEX 1 2 Lab Manual - Software Design Laboratory IDENTIFIER a I 26 VPCOE, Baramati Lexical Analyzer 3. Literal Table (LIT) INDEX 1 2 LITERAL 10 5 4. Uniform Symbol Table (UST) TOKEN if ( a ¡ 10 ) I = a + 5 ; 4.5 CLASS OF TOKEN TRM TRM IDN TRM LIT TRM IDN TRM IDN TRM LIT TRM INDEX IN THEIR TABLE 3 11 1 21 1 12 2 23 1 17 2 15 Conclusion Lexical analysis is the process of converting a sequence of characters into a sequence of tokens. A program or function which performs lexical analysis is called a lexical analyzer, lexer or scanner. With the help of this assignment we have performed the tokenization of the expressions in the C programming language. 4.6 Post Lab Following objectives are met • To understand the role of Lexical Analyzer 4.7 Viva Questions 1. Explain phase of compiler. 2. Explain symbol table. Lab Manual - Software Design Laboratory 27 VPCOE, Baramati Lexical Analyzer 3. Explain lexical analysis. 4. What is token? 5. What is identifier? 6. What is UST? Lab Manual - Software Design Laboratory 28 VPCOE, Baramati Assignment 5 Recursive Descent parser 5.1 Problem Statement Study of Recursive Descent parser 5.2 Pre Lab • Concept of Top down parser. • Process of backtracking should be known to student. 5.3 Theory 5.3.1 Parsing Parsing is the task of determine the syntax or structure of a program. The goals of parsing are to check the validity of a source string and to determine its syntactic structure. For a valid string it builds a parse tree to reflect the sequence of derivations or reductions performed during parsing. 5.3.2 Types of parser The task of the parser is essentially to determine if and how the input can be derived from the start symbol of the grammar. This can be done in essentially two ways: 1. Top-down parsing- Top-down parsing can be viewed as an attempt to find left-most derivations of an input-stream by searching for parse trees using a top-down expansion of the given formal 29 Recursive Descent parser grammar rules. Tokens are consumed from left to right. Examples: Recursive descent parser, Predictive parser 2. Bottom-up parsing - A parser can start with the input and attempt to rewrite it to the start symbol. Intuitively, the parser attempts to locate the most basic elements, then the elements containing these, and so on. Examples: Shift reduce parser, LR Parser 5.3.3 Recursive descent parser It is a top-down parser built from a set of mutually-recursive procedures (or a non-recursive equivalent) where each such procedure usually implements one of the production rules of the grammar. Thus the structure of the resulting program closely mirrors that of the grammar it recognizes. It can be viewed as an attempt to find a leftmost derivation for an input string. Also it can be viewed as an attempt to construct a parse tree for the input starting from the root and proceeding towards the leaves. The recursive descent parsing may involve backtracking i.e. making repeated scans of the input. Backtracking may cause many problems which are overcome by rewriting the grammar and using predictive parser. e.g. Consider the grammar S -> c A d A-> a b | a and input string w = cad To construct parse tree start with tree with single node ’S’. An input pointer points to ’c’, the first symbol of ’w’. Then expand the tree using first production for ’S’ as follows Lab Manual - Software Design Laboratory 30 VPCOE, Baramati Recursive Descent parser The leftmost leaf ’c’ matches the first symbol of ’w’ so advance the input pointer to ’a’ and consider the next leaf labeled ’A’. Expand ’A’ using the first alternative for ’A’ to obtain the tree as follows Now match is found for second input symbol so advance the input pointer to ’d’ and compare ’d’ against the next leaf ’b’. Since ’b’ doesn’t match ’d’ report an error and go back to ’A’ to check for another possible alternative. In going back to ’A’ reset the input pointer to previous position. Now try the second alternative for ’A’ to obtain the tree as follows Now the leaf ’a’ matches the second symbol of ’w’ and the leaf ’d’ matches the third symbol. Since the parse tree is produced for ’w’, halt and announce successful completion of parsing. 5.3.4 Predictive parser It is a recursive descent parser that does not require backtracking. Predictive parsing is possible only for the class of LL (k) grammars, which are the context-free grammars for which there exists some positive integer k that allows a recursive descent parser to decide which production to use by examining only the next k tokens of input 5.3.5 Predictive Parsing-LL (1) Parsers The first ’L’ refers to the fact that it processes the input from left to right. The second ’L’ refers to the fact that it produces leftmost derivation for the input string. The number ’1’ in the parentheses means Lab Manual - Software Design Laboratory 31 VPCOE, Baramati Recursive Descent parser that it uses only one symbol of input to predict the direction of parse. The LL (1) parsing uses an explicit stack. e.g. Consider the grammar S → (S)S | ε The input string is w= ( ) Parsing Stack- Bottom of stack is to the left and top of the stack is to right. Mark bottom of stack with ’$ ’. Stack containing non-terminal S at the top appears as ’ $S ’. Additional stack items would be pushed on right. Input- Contains input string. The input symbols are listed from left to right. The dollar sign ’$ ’ is used to mark the end of input. Action- Actions taken by parser which will change stack and input contents. The parser begins by parsing the start symbol onto the stack. It accepts input string if after the series of actions the stack and input become empty. In the above example, the start symbol is ’S’ and input string is ’( )’ • Replace ’S’ with proper rule. (a → β) • Push the RHS of rule in reverse order onto stack to ensure that the string β will come to the top of the stack in left to right order. • Match a token on top of the stack with input token and throw away both by popping stack and advancing the input. 5.4 Conclusion By carefully writing the grammar, eliminating left recursion from it and left factoring the resulting grammar, we can obtain a grammar that can be parsed by a recursive descent parser that needs no Lab Manual - Software Design Laboratory 32 VPCOE, Baramati Recursive Descent parser backtracking i.e. a predictive parser. 5.5 Post Lab Following objectives are met • To understand the process of parsing and to study bottom-up and top down parsing. 5.6 Viva Questions 1. Define parsing. 2. Explain problems with its solution of recursive descent parser. Lab Manual - Software Design Laboratory 33 VPCOE, Baramati Assignment 6 Calculator using LEX and YACC 6.1 Problem Statement Implementation of Calculator using LEX and YACC. 6.2 Pre Lab • Concept of LEX and YACC program structure. • Compilation and execution process should be known to student. 6.3 Hardware and Software Requirement • Software Requirement – Lex and YACC tools 6.4 6.4.1 Theory Introduction Lex is a tool widely used to specify lexical analyzers for variety of languages. The tool shows how the speciation of patterns using regular expression can be combined with actions that LA may be required to perform. 34 Calculator using LEX and YACC 6.4.2 Lex Specification Specification of Lexical Analyzer is prepared by creating a program lex.1 in Lex language. Lex.1 is run through Lex compilers to produce lex.yy.c which consist of a tabular representation of transition diagram constructed from regular expression of Lex.1, together with a standard routine that uses the table to recognize lexemes actions associated with regular expressions in lex.l. Also pieces of C code are carried over directly to Lex.yy.c. Finally lex.yy.c is run through C compiler to produce a.out which is the lexical analyzer that transforms an input stream into a sequence of tokens. Lex Specifications: Lex program consist of 3 parts Declarations %% Transition Rules %% Auxiliary Procedures 6.4.3 Parser Generators YACC - yet another compiler - compile facilitates the construction of front end of the compiler. Lab Manual - Software Design Laboratory 35 VPCOE, Baramati Calculator using LEX and YACC YACC source program has 3 parts:Declarations %% Transition rules %% Supporting C routines Declaration Part1. Ordinary ’C’ declarations within % { %} 2. Token Declarations Translation rules part- Each translation rule consist of a grammar production and associated semantic action. E.g. expr : | expr expr ’+’ expr { $$ = $1 + ’-’ expr { $$ = $1 - $3; } $3; } ; 1. ’+’,’-’ are quoted single characters of type ’c’ and are treated as terminal symbols 2. Unquoted strings of letters and digits not declared to be tokens are taken as non-terminals -expr. Lab Manual - Software Design Laboratory 36 VPCOE, Baramati Calculator using LEX and YACC 3. Alternative right sides can be separated by a vertical bar and a semicolon follows each left side with its alternatives and their semantic actions first left side is taken as start symbol. YACC semantic action is a sequence of ’C’ statements. In semantic action $$ refers to the value associated with non terminal on left and while $i refers to the value associated with ith grammar symbol [T \ NT] on right. 6.4.4 Communication between Lex and YACC Yylex () produces pairs containing token and its associated value. If token NUMBER is returned then the token NUMBER must be declared in first section of YACC. The attribute value associated with a token is communicated to the parser through YACC defined variable yylval. 6.5 Conclusion Lex recognizes the regular expressions, divides the input stream into tokens and then Yacc takes these tokens and groups them together logically by recognizing entire grammar. 6.6 Post Lab Following objectives are met • To understand the role of LEX and YACC. 6.7 Viva Questions 1. Explain Lex. 2. Explain Yacc. 3. Explain the parts of lex and yacc program. Lab Manual - Software Design Laboratory 37 VPCOE, Baramati Assignment 7 Screen Editor 7.1 Problem Statement Implement Screen Editor with following Features: 1. Open an existing file 2. Create and Save the current file. 3. All cursor movements up, down, left, right arrow keys 4. Delete and backspace keys. 7.2 Pre Lab • Student should be familiar with computer graphics concepts and its implementation in C. 7.3 7.3.1 Theory Editor and Types of Editor Editors are program entry and editing tool through which programs are entered into the computer. It allows creation, update and deletion of items in a file. A typical editor’s GUI has a menu bar, a set of buttons on various toolbars, other controls and finally a large ”canvas” area for display and direct manipulation of the document. Text editors come in following form: 1. Line editors 2. Stream editors 38 Screen Editor 3. Screen editors 4. Word processors 5. Structure editors Line editor is a text editor computer program that is oriented around lines. The line editor supports editing operations where basic unit is a line. Example: UNIX ed editor Stream editor views the entire text as a stream of characters. Screen editor uses the ’What-You-See-Is-What-You-Get’ principle in editor design. It displays a screenful of text at a time where text is conceptually split into screens. Word Processors are document editors with additional features to produce well formatted hardcopy output. Structure editors can be used to edit hierarchical or marked up text, computer programs, diagrams, chemical formulas, and any other type of content with clear and well-defined structure. Structure editing predominates when content is graphical and textual representations are awkward. Example: CAD systems and PowerPoint. 7.3.2 Design of an Editor The fundamental functions in editing are traveling, editing, viewing and display. Traveling implies movement within the text. Viewing implies formatting the text in a manner desired by user. This is an abstract view, independent of the physical characteristics of an IO device. Display component maps this view into physical characteristics of display device being used. Editing allows changes in text. Figure illustrates the schematic of a simple editor. For a given position of the editing context, the editing and viewing filters operate on the internal form of text to prepare the forms suitable for editing and viewing. These forms are put in the editing and viewing buffers respectively. The viewingand-display manager makes provision for appropriate display of this text. When the cursor position changes; the filters operate on a new portion of text to update the contents of the buffers. As editing is performed, the editing filter reflects the changes into the internal form and updates the contents of the viewing buffer. Lab Manual - Software Design Laboratory 39 VPCOE, Baramati Screen Editor Figure 7.1: Design of an Editor 7.4 Procedure 7.4.1 Algorithm 1. Start 2. Initialize a string storing to file contents 3. Initialize cursor position as row and columns value to 3,2 4. Call displaymenu function 5. Display current cursor position 6. Accept key from user and perform action depending on the key value as: Lab Manual - Software Design Laboratory 40 VPCOE, Baramati Screen Editor (a) If backspace is entered, decrement row value, print space and decrement row again. In the string store decrement pointer position and store space. (b) If enter key is pressed , make row size to maximum x value. Store \n in array for that position. 7. If entered key is (a) Upword arrow, decrement column value and take pointer in string to point that character (b) Downword arrow, increment column value and take pointer in string to point that character (c) Left arrow, decrement row and ptr value (d) Right arrow, increment row and ptr value 8. If Alt+f is pressed, call dispfile function. 9. If Alt+h is pressed, call disphelp function. 10. If other than this key is pressed, display the value and store it in the string. 11. Repeat from step 5 till Esc key is not pressed. 12. Stop 7.4.2 Function :dispmenu() 1. Start 2. Open a window of screen size. 3. On top of window take the cursor to print menu bar 4. Stop 7.4.3 Function :dispfile() 1. Start 2. Open a window with file options 3. Depending on option selected by user perform function 4. For NEW option (a) Clear the screen (b) Call dispmenu function Lab Manual - Software Design Laboratory 41 VPCOE, Baramati Screen Editor (c) Open a window with name in middle as ’noname.c’ (d) Initialize the cursor position to start of page 5. For OPEN option (a) Clear the screen (b) Call dispmenu function (c) Accept file name (d) Open the file (e) If file pointer returns NULL display message ’file does not exist’ (f) Else, open the file in read mode, print the file and store the characters in the string 6. For SAVE option (a) If function is set indicating that new file then accept the file name (b) Open the file in write mode (c) Write the string contents (d) Close the file 7. For SAVEAS option (a) Accept the file name (b) Open the file in write mode (c) Write the string contents (d) Close the file 8. For EXIT option (a) Check if opened file is not saved or new file is not saved (b) Ask user whether to save, if yes call save option (c) Else exit 9. Stop Lab Manual - Software Design Laboratory 42 VPCOE, Baramati Screen Editor 7.4.4 Function :disphelp() 1. Start 2. Open a window 3. Display command and corresponding key 4. Stop 7.5 Conclusion The following features of screen editor are studied with the help of this implementation 1. Text is conceptually split into screen 2. The user has full control over entire terminal where screen is displayed 3. The user can move cursor over screen for editing operations 4. The user can bring delete a character by pressing delete or backspace key 7.6 Post Lab Following objectives are met • To understand the role of Screen Editor in language processing 7.7 Viva Questions 1. Define Screen Editor. 2. What are the different categories of editors? 3. What is difference between line editor and screen editor? 4. Explain design of screen editor. Lab Manual - Software Design Laboratory 43 VPCOE, Baramati Assignment 8 Dyanamic Link Library 8.1 Problem Statement Implementation of DLL. 8.2 Pre Lab • Student should be familiar with Visual Basic and VC++ tool. 8.3 Hardware and Software Requirement • Software Requirement – Visual Basic 6.0 8.4 Theory Visual basic or visual studio is very fast and easy tool for developing applications with high degree of user friendliness , but it lacks some important functionalities like direct access to hardware, multi threading(Activex servers allows some type of multi threading !). The easy and effective solution for this problem is to write a DLL. 8.4.1 What is Static linking and Dynamic linking? The libraries can be linked to the executable in two ways. One is static linking and the other is dynamic linking. Static linking is the method used to combine the library routines with the application. When building the program, the linker will search all the libraries for the unresolved functions called in the 44 Dyanamic Link Library program and if found, it will copy the corresponding object code from the library and append it to the executable. The linker will keep searching until there are no more unresolved function references. This is the most common method for linking libraries. This method boasts of ease of implementation and speed but will generate bulky executable. In dynamic linking, the required functions are compiled and stored in a library with extension .DLL. Unlike static linking, no object code is copied in to the executable from the libraries. Instead of that, the executable will keep the name of the DLL in which the required function resides and when the executable is running, it will load the DLL and call the required functions from it. This method yields an executable with small footprint, but has to compromise on speed a little. Using DLLs is a great way to reuse code. Rather than re-implementing the same routines in every program that you create, you write them one time and reference them from applications that need the functionality. DLL is not a self executable; it is called as library file. The code written in DLL file is substituted into exe.It is similar to header file in C language. 8.4.2 Example Objective Create a Dynamically linkable library which can calculate and return the sum of two numbers passed to it. Tools required visual C++ 6, Visual basic 6 Writing The DLL Start VC++ IDE, and select New from File menu. Then select Win32 Dynamic - link library from Projects tab (Figure 8.1). Figure 8.1: Lab Manual - Software Design Laboratory 45 VPCOE, Baramati Dyanamic Link Library Enter project name as example1, then click OK button. Now you can see a dialog box with caption Win32 Dynamic - Link library - step 1 of 1 (Figure 8.2). Figure 8.2: Select a simple DLL project and click Finish. Now open exaple1.cpp from file view (Figure 8.3) Figure 8.3: Add these lines in to example1.cpp int _stdcall sum(int x , int y) { return x+y; } It is a simple function which returns the sum of numbers passed to it. Now our function is ready. The next step is to create a ’.def’ file which informs the linker to export our function. Select New from Lab Manual - Software Design Laboratory 46 VPCOE, Baramati Dyanamic Link Library File menu and then select text File from Files tab. Give it a name example1.def. Now you can see an empty file. Add these lines in to example1.def LIBRARY EXAMPLE1 EXPORTS sum @1 Select Build example1.dll from build menu. The build process should complete without any errors. If any error occurs, correct it and rebuild again. Once the build process is completed successfully, you can see example1.dll in debug directory. Now we have successfully built the Dll and it is the time to test it. For testing the DLL we have to write a small program in VB. Open a new project in Visual Basic. Place three text box and a command button like in Figure 8.4. Figure 8.4: Copy the code given bellow , to the code window Private Declare Function sum Lib "example1.dll" (ByVal x As Long, ByVal y As Long) As Long Private Sub Command1_Click() Text3.Text = Str(sum(CInt(Text1.Text), CInt(Text2.Text))) End Sub copy example 1.dll to windows or system directory . Then run VB, enter some values to text1 and text2 and click Calculate button. If you can see the sum in text3, you have completed example1 successfully! 8.4.3 Required Files 1. A .cpp file contains entry points for the functions 2. A module-definition (.def) file is a text file containing one or more module statements that describe various attributes of a DLL. The DLL requires a .def file to export the DLL’s functions. A minimal .def file must contain the following module-definition statements: Lab Manual - Software Design Laboratory 47 VPCOE, Baramati Dyanamic Link Library 3. The first statement in the file must be the LIBRARY statement. This statement identifies the .def file as belonging to a DLL. The LIBRARY statement is followed by the name of the DLL. The linker places this name in the DLL’s import library. 4. The EXPORTS statement lists the names and, optionally, the ordinal values of the functions exported by the DLL. You assign the function an ordinal value by following the function’s name with an at sign (@) and a number. When you specify ordinal values, they must be in the range 1 through N, where N is the number of functions exported by the DLL. 8.5 Conclusion By implementing above assignment we can conclude following points: 1. If the programmer has to use same line of instructions (code) for different applications it will be time consuming and wastage of memory. So common lines of instruction are packaged into dll file and can be provided to different application for its development. 2. If any changes to be carried out, the programmer has no need to make changes to each and every application folder, just make the to dll file and provides to different application. The changes to dll will reflect to all the application, which provides better maintenance. 3. Language Interoperability i.e. using one language code in another language can be achieved. 8.6 Post Lab Following objectives are met • To understand the role of DLL. 8.7 Viva Questions 1. Explain what is meant by DLL. 2. Explain- the need for DLL. 3. Explain various types DLL. Compare them. 4. Where the system’s DLL are located? 5. Which files you have used to create DLL? Lab Manual - Software Design Laboratory 48 VPCOE, Baramati Dyanamic Link Library PART-B Design and Analysis of Algorithms Lab Manual - Software Design Laboratory 49 VPCOE, Baramati Assignment 9 Tower of Hanoi 9.1 Problem Statement Solve Tower of Hanoi problem by using Recursive Divide and Conquer strategy. 9.2 Pre Lab • Concept of Tower of Hanoi problem • Concept of Recursion 9.3 Theory 9.3.1 Introduction The Tower of Hanoi or Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: 1. Only one disk may be moved at a time. 2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. 3. No disk may be placed on top of a smaller disk 50 Tower of Hanoi 9.3.2 Recursive solution A key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems until a solution is reached. The following procedure demonstrates this approach. 1. Label the rods A, B, C-these labels may move at different steps 2. Let n be the total number of discs 3. Number the discs from 1 (smallest, topmost) to n (largest, bottommost) To move n discs from rod A to rod C: 1. Step 1: If n¿1 then first use this procedure to move the n-1 smaller disks from rod A to rod B. 2. Step 2: Now the largest disk, i.e. disk n-1 can be moved from rod A to rod C. 3. Step 3: If n¿1 then again use this procedure to move the n-1 smaller disks from rod B to rod C. The above is a recursive algorithm: to carry out steps 1 and 3, apply the same algorithm again for n-1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This approach can be given a rigorous mathematical formalism with the theory of dynamic programming. Using recurrence relations, the exact number of moves that this solution requires can be calculated by: 2n - 1 as shown below. This result is obtained by noting that steps 1 and 3 take T(n-1) moves, and step 2 takes one move, giving Solving above recurrence by repeatedly substitution methodT(n) = 2 T( n-1 ) +1 T(n) = 2 [ 2 T(n-2) + 1 ] +1 T(n)=4T(n-2)+3 T(n) = 4 [ 2 T(n-3) + 1 ]+3 T(n)=8T(n-3)+7 . . . . . . T(n) = 2k T ( n-k ) + 2k - 1 T(n)= 2k [ T ( n-k ) + 1 ] - 1 Since n is finite, k tends to n. Therefore, T (n) = 2n - 1 Lab Manual - Software Design Laboratory 51 VPCOE, Baramati Tower of Hanoi 9.4 Procedure Input: No of Disk, No of Pegs (fixed 3) Output: No of required moves, Total time to solve problem void hanoi (int x, char from, char to, char aux) //Takes 4 parameters i.e. disk, Peg ’A’, Peg ’C’, Peg ’B’ { if(x==1) { printf ("Move Disk From %c to %c\n", from,to); } else { hanoi(x-1, from, aux,to); printf ("Move Disk From %c to %c\n", from,to); hanoi(x-1, aux, to,from); } } 9.5 Conclusion We can solve the problem of Tower of Hanoi by using Recursive Divide and Conquer programming strategy. 9.6 Post Lab Following objectives are met • To understand the process of recursion. • To understand the role of Divide and conquer strategy in programming. 9.7 Viva Questions 1. Explain what is meant by recursion. 2. Explain- the need for recursion. 3. Solve recurrence relation for Tower of Hanoi. Lab Manual - Software Design Laboratory 52 VPCOE, Baramati Assignment 10 Kruskal’s algorithm 10.1 Problem Statement Implement Kruskal’s algorithm by using greedy programming strategy. 10.2 Pre Lab • Concept of minimum spanning tree and Kruskal’s algorithm. 10.3 Theory 10.3.1 Introduction to greedy algorithm A greedy algorithm is any algorithm that follows the problem solving heuristic method of making the locally optimal choice at each stage with the hope of finding the global optimum solution. In general, greedy algorithms have five pillars: 1. A candidate set, from which a solution is created 2. A selection function, which chooses the best candidate to be added to the solution 3. A feasibility function that is used to determine if a candidate can be used to contribute to a solution 4. An objective function, which assigns a value to a solution, or a partial solution, and 5. A solution function, which will indicate when we have discovered a complete solution Examples of greedy algorithms- 53 Kruskal’s algorithm 1. Kruskal’s algorithm and Prim’s algorithm for finding minimum spanning trees, 2. Dijkstra’s algorithm for finding single-source shortest paths, 3. Algorithm for finding optimum Huffman trees. 10.3.2 Kruskal’s algorithm for finding Minimum Spanning Tree The input is a connected graph, G, with n vertices and m edges with non-negative weights, w (ei ). The output is a spanning tree, T, whose total weight is a minimum. The number of vertices in T is denoted V (T). We first sort the edges such that w (e1 ) <w (e2 ) <. <w (em ). Then at each step of algorithm an edge with minimum weight is added to T such that it should not form the cycle otherwise edge is discarded. 10.4 Procedure 1. Create a set of trees F, where each vertex in the graph is a separate tree. 2. Create a set S containing all the edges in the graph. 3. While S is nonempty and F is not yet spanning remove an edge with minimum weight from S 4. If that edge connects two different trees, then add it to the forest, combining two trees into a single tree. Otherwise discard that edge. 5. At the termination of the algorithm, the forest has only one component and forms a minimum spanning tree of the graph. 10.5 Sample Input/Output Sample Input: Input Graph: Lab Manual - Software Design Laboratory 54 VPCOE, Baramati Kruskal’s algorithm Sample output: MST Using Kruskal’s Algorithm: 10.6 Conclusion Kruskal’s algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex of the graph, where the total weight of all the edges in the tree is minimized. Kruskal’s algorithm is an example of a greedy algorithm. 10.7 Post Lab Following objectives are met • To understand the greedy programming approach. • To understand the difference between greedy and dynamic approach. 10.8 Viva Questions 1. Explain what is meant by greedy strategy. 2. Explain how greedy strategy is used in Kruskal’s algorithm. 3. Explain various steps in greedy programming. 4. How greedy differs from dynamic strategy? Lab Manual - Software Design Laboratory 55 VPCOE, Baramati Assignment 11 8 Queen Problem 11.1 Problem Statement Solve the 8 Queen Problem by using backtracking programming strategy. 11.2 Pre Lab • Concept of 8 Queen problems. • Concept of recursion. 11.3 Theory 11.3.1 Backtracking Many problems which deal with searching for a set of solutions or which ask for an optimal solution satisfying some constraints can be solved using the backtracking formulation. In many applications of the backtrack method, the desired solution is expressible as an n-tuple (x1 , x2 ,, xn ), where the xi are chosen from some finite set Si . 11.3.2 The 8-Queen Problem The eight queens puzzle is the problem of placing eight chess queens on an 88 chessboard so that no two queens attack each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general n-queens problem of placing n queens on an nn chessboard, where solutions exist only for n = 1 or n ≥ 4. 56 8 Queen Problem Let (x1 , x2 .., xn ) represent the solution in which xi is the column of the it h row where it h queen is placed. The xi ’s will all be distinct since no two queens can be placed in the same column. Also test should be done to make sure that no two queens are on the same diagonal. Suppose two queens are placed at positions (i,j) and (k,l). Then they are on the same diagonal only if i-j = k-l or i+j = k+l The first equation implies j-l = i-k The second equation implies j-l = k-i Therefore two queens lie on the same diagonal if and only if |j-l|=|i-k| 11.3.3 Basic idea of solution 1. Start with one queen in the first column, first row. 2. Start with another queen in the second column, first row. 3. Go down with the second queen until you reach a permissible situation. 4. Advance to the next column, first row, and do the same thing. 5. If you cannot find a permissible situation in one column and reach the bottom of it, then you have to go back to the previous column and move one position down there. (This is the backtracking step.) 6. If you reach a permissible situation in the last column of the board, then the problem is solved. 7. If you have to backtrack BEFORE the first column, then the problem is not solvable. 11.4 Procedure Algorithm NQueens(k,n) //Using backtracking this procedure prints all possible placements of n queens on an n x n //chessboard so that they are nonattacking. { for i=1 to n do { Lab Manual - Software Design Laboratory 57 VPCOE, Baramati 8 Queen Problem if Place(k,i) then { x[k]=i; if (k=n) then write (x[1:n]); else NQueens(k+1,n); } } } Algorithm Place(k,i) //Returns true if a queen can be placed in kth row and ith column. Otherwise it returns false. //X[] is a global array whose first (k-1) values have been set. Abs returns the absolute value of r. { for j=1 to k-1 do if ((x[j]=i) //Two in the same column or (Abs(x[j]-i)=Abs(j-k))) //or in the same diagonal then return false; return true; } 11.5 Conclusion The algorithm to solve this problem uses backtracking. The basic idea is to place queens column by column, starting at the left. New queens must not be attacked by the ones to the left that have already been placed on the board. We place another queen in the next column if a consistent position is found. All rows in the current column are checked. We have found a solution if we placed a queen in the rightmost column. 11.6 Post Lab Following objectives are met • To understand the backtracking programming approach. • To understand how to use recursion techniques to implement backtrack. Lab Manual - Software Design Laboratory 58 VPCOE, Baramati 8 Queen Problem 11.7 Viva Questions 1. Explain what is meant by backtracking strategy. 2. Explain how backtracking is implemented in above algorithm. 3. Explain the conditions to check the feasibility of placement of queen. Lab Manual - Software Design Laboratory 59 VPCOE, Baramati References [1] D.M. Dhamdhere, ”Systems Programming and Operating Systems”, Tata McGraw-Hill. [2] John J Donovan, ”Systems Programming”, Tata McGraw-Hill, 1991. [3] Alfred V. Aho, Ravi Sethi, Reffrey D. Ullman, ”Compilers Principles, Techniques, and Tools”, Addison Wesley. [4] John R. Levine, Tony Mason, Doug Brown, ”lex and yacc”, O’REILLY. 60