CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENT- 1 AIM: Write a program to insert a new element at end as well as at a given position in an array. OBJECTIVE: To understand how to insert an element into an array using the concept of index. PREREQUISITES: for loop, Traversing of an array and insertion at beginning of an array. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: 1) First get the element to be inserted, say x 2) Then get the position at which this element is to be inserted, say pos 3) Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos. 4) Insert the element x now at the position pos, as this is now empty. ALGORITHM: Assume that A is an array with N elements. The maximum numbers of elements it can store is defined by MAX. begin IF N = MAX, return ELSE N=N+1 SEEK Location index For All Elements from A[index] to A[N] Move to next adjacent location A[index] = New_Element End 1 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING SOURCE CODE: Following is source code of the C++ Program to Insert an element in an array at specific position. The C++ program is successfully compiled and run(on Codeblocks) on a Windows system. #include<iostream> using namespace std; int main( ) { int arr[50], size, insert, i, pos; cout<<"Enter Array Size : "; cin>>size; cout<<"Enter array elements : "; for(i=0; i<size; i++) { cin>>arr[i]; } cout<<"Enter element to be insert : "; cin>>insert; cout<<"At which position (Enter index number) ? "; cin>>pos; // now create a space at the required position for(i=size; i>pos; i--) { arr[i]=arr[i-1]; } arr[pos]=insert; cout<<"Element inserted successfully..!!\n"; cout<<"Now the new array is : \n"; for(i=0; i<size+1; i++) { cout<<arr[i]<<" "; } 2 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING return 0; } EXPERIMENTAL PROCEDURE: After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: (a) Insertion at the end: (b) Insertion at a given position: 3 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CONCLUSION: We have successfully learned how to insert an element in to an array at a given position(at the end, beginning or at any index value EXPERIMENT-2 AIM: Write a program to delete an element from a given array whose value is given or whose position is given. OBJECTIVE: To understand how to delete an element from an array using the concept of index and value, both. PREREQUISITES: for loop and insertion in an array. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: Step by step descriptive logic to remove element from array. 1) Move to the specified location which you want to remove in given array. 2) Copy the next element to the current element of array. Which is you need to perform array[i] = array[i + 1]. 3) Repeat above steps till last element of array. 4 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING 4) Finally decrement the size of array by one. a) /* C++ Program - Delete Element(value provided) from Array */ #include<iostream> using namespace std; int main() { int arr[50], size, i, del, count=0; cout<<"Enter array size : "; cin>>size; cout<<"Enter array elements : "; for(i=0; i<size; i++) { cin>>arr[i]; } 5 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING cout<<"Enter element to be delete : "; cin>>del; for(i=0; i<size; i++) { if(arr[i]==del) { for(int j=i; j<(size-1); j++) { arr[j]=arr[j+1]; } count++; break; } } if(count==0) { cout<<"Element not found..!!"; } else { cout<<"Element deleted successfully..!!\n"; cout<<"Now the new array is :\n"; for(i=0; i<(size-1); i++) { cout<<arr[i]<<" "; } return 0; } } EXPERIMENTAL PROCEDURE: 6 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: b) /* C++ Program - Delete Element(position provided) from Array */ #include <iostream> using namespace std; int main() { int a[10], size, pos, i, count = 0; cout << "Enter the size of an array \n"; cin >> size; cout << "Enter the value in an array \n"; // Take an input array for (i = 0; i < size; i++) { cin >> a[i]; } 7 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING //Input position where we delete an element cout << "Enter the position \n"; cin >> pos; //Shift element from i+1 to i for(i = pos-1; i < size; i++) { a[i] = a[i+1]; } // Reduce the size of an array size--; // Print an array after deleting an element for(i = 0; i < size; i++) { cout<<" "<<a[i]; } return 0; } OUTPUT: CONCLUSION: We have successfully learned how to delete an element from a given array using its value and using its index separately. 8 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENT -3 AIM: Write a program to find the location of a given element using Linear Search. OBJECTIVE: To learn how to search the location of a particular element in an array using the linear search algorithm. PREREQUISITES: for loop and Traversing of an array. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: 9 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any search is said to be successful or unsuccessful depending upon whether the element that is being searched is found or not. Linear Search : Linear search is a very basic and simple search algorithm. It traverses the array sequentially to locate the required element. It searches for an element by comparing it with each element of the array one by one. So, it is also called as Sequential Search. Linear Search Algorithm is applied whenNo information is given about the array. The list of data items is smaller. Linear search is implemented using following steps: 1) Read the search element from the user. 2) Compare the search element with the first element in the list. 3) If both are matched, then display "Given element is found!!!" and terminate the function. 4) If both are not matched, then compare search element with the next element in the list. 5) Repeat steps 3 and 4 until search element is compared with last element in the list. 6) If last element in the list also doesn't match, then display "Element is not found!!!" and terminate the function. ALGORITHM: Consider• There is a linear array ‘a’ of size ‘n’. • Linear search algorithm is being used to search an element ‘item’ in this linear array. 10 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING • If search ends in success, it sets loc to the index of the element otherwise it sets loc to 1. Then, Linear Search Algorithm is as followsLinear_Search (a , n , item , loc) for i = 0 to (n - 1) by 1 if (a[i] = item) set loc = i; else set loc = -1; SOURCE CODE: #include<iostream> using namespace std; int main() { int a[20],n,x,i,flag=0; cout<<"How many elements?"; cin>>n; cout<<"\n Enter elements of the array \n"; for(i=0;i<n;++i) cin>>a[i]; cout<<"\n Enter element to search:"; cin>>x; for(i=0;i<n;++i) { 11 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING if(a[i]==x) { flag=1; break; } } if(flag) cout<<"\n Element is found at position "<<i+1; else cout<<"\n Element not found"; return 0; } EXPERIMENTAL PROCEDUREAfter writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: 12 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CONCLUSION: Linear search algorithm has been implemented successfully to find the location of a given element in an array. 13 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENT -4 AIM: Write a program to find the location of a given element using Binary Search. OBJECTIVE: To learn how to search the location of a particular element in an array using the binary search algorithm. PREREQUISITES: for loop, Linear search algorithm RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: Binary search is one of the fastest searching algorithms. It is used for finding the location of an element in a linear array. It works on the principle of divide and conquer technique. Binary Search Algorithm can be applied only on Sorted arrays. So, the elements must be arranged inEither ascending order if the elements are numbers. Or dictionary order if the elements are strings. To apply binary search on an unsorted array: First, sort the array using some sorting technique. Then, use binary search algorithm. Consider- 14 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING There is a linear array ‘a’ of size ‘n’. Binary search algorithm is being used to search an element ‘item’ in this linear array. If search ends in success, it sets loc to the index of the element otherwise it sets loc to 1. Variables beg and end keeps track of the index of the first and last element of the array or sub array in which the element is being searched at that instant. Variable mid keeps track of the index of the middle element of that array or sub array in which the element is being searched at that instant. Binary search algorithm searches an element by comparing it with the middle most element of the array. Then, following three cases are possibleCase-01: If the element being searched is found to be the middle most element, its index is returned. Case-02: If the element being searched is found to be greater than the middle most element, then its search is further continued in the right sub array of the middle most element. Case-03: If the element being searched is found to be smaller than the middle most element, then its search is further continued in the left sub array of the middle most element. This iteration keeps on repeating on the sub arrays until the desired element is found OR size of the sub array reduces to zero. ALGORITHM: BinarySearch(DATA,BEG,END,LOC,MID,ITEM) DATA is a sorted array with lower bound LB & upper bound UB, and ITEM is given item of information to be searched. The variables BEG, END and MID denote, respectively, the 15 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING beginning, the end and the middle locations of an array. This algorithm finds the location LOC of ITEM in DATA or sets LOC to NULL. 1) Set BEG:= LB,END:=UB and MID:=INT((BEG+END)/2). 2) Repeat steps 3 & 4 while BEG≤END and DATA[MID]≠ITEM. 3) If ITEM <DATA[MID],then: Set END:=MID-1 else Set BEG:=MID+1 4) Set MID:=INT((BEG+END)/2). 5) If DATA[MID]=ITEM, then Set LOC:=MID else Set LOC:=NULL 6) Exit. SOURCE CODE: #include <iostream> using namespace std; int main( ) { int count, i, arr[20], num, first, last, mid; cout<<"how many elements would you like to enter?:"; cin>>count; for (i=0; i<count; i++) { cout<<"enter number "<<(i+1)<<": "; cin>>arr[i]; 16 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING } cout<<"enter the number that you want to search:"; cin>>num; first = 0; last = count-1; mid = (first+last)/2; while (first <= last) { if(arr[mid] < num) { first = mid + 1; } else if(arr[mid] == num) { cout<<num<<" found in the array at the location "<<mid+1<<"\n"; break; } else { last = mid - 1; } mid = (first + last)/2; } if(first > last) { cout<<num<<" not found in the array"; } return 0; 17 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING } EXPERIMENTAL PROCEDURE: After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: CONCLUSION: Binary search algorithm has been successfully implemented to find location of a given element on a sorted array. 18 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENT -5 AIM: Write a program to implement push and pop operations on a stack using linear array. OBJECTIVE: To understand & perform insertion(PUSH) & deletion(POP) operations in a stack using an array. PREREQUISITES: for loop and array traversal. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc. Stack ADT allows all data operations at one end only. At any given time, we can only access the top element of a stack. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation. The 19 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING following diagram depicts a stack and its operations – PUSH OPERATION: The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a series of steps − Step 1 − Checks if the stack is full. Step 2 − If the stack is full, produces an error and exit. Step 3 − If the stack is not full, increments top to point next empty space. Step 4 − Adds data element to the stack location, where top is pointing. Step 5 − Returns success. ALGORITHM FOR PUSH OPERATION: A simple algorithm for Push operation can be derived as follows – PUSH(STACK,TOP,MAXSTK,ITEM) 1) If TOP=MAXSTK, then PRINT: “OVERFLOW” and return. 2) Set TOP:= TOP + 1 3) Set STACK[TOP]:= ITEM 4) Return POP OPERATION: Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value. A Pop operation may involve the following steps − Step 1 − Checks if the stack is empty. Step 2 − If the stack is empty, produces an error and exit. Step 3 − If the stack is not empty, accesses the data element at which top is pointing. Step 4 − Decreases the value of top by 1. 20 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Step 5 − Returns success. ALGORITHM FOR POP OPERATION: A simple algorithm for Pop operation can be derived as follows – POP(STACK,TOP,ITEM) 1) If TOP=0,then PRINT: “UNDERFLOW” and return. 2) Set ITEM:= STACK[TOP] 3) Set TOP:= TOP - 1 4) Return SOURCE CODE: #include <iostream> using namespace std; int stack[20], n = 20, top = -1; void push(int val) { if(top >= n-1) cout<<"stack overflow"<<endl; else { top++; stack[top] = val; } } void pop() { if(top <= -1) cout<<"stack underflow"<<endl; else { cout<<"the popped element is "<< stack[top] <<endl; 21 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING top--; } } void display() { if(top>= 0) { cout<<"stack elements are:"; for(int i = top; i>= 0; i--) cout<<stack[i]<<" "; cout<<endl; } else cout<<"stack is empty"; } int main() { int ch, val; cout<<"1) push in stack"<<endl; cout<<"2) pop from stack"<<endl; cout<<"3) display stack"<<endl; cout<<"4) exit"<<endl; do { cout<<"enter choice: "<<endl; cin>>ch; switch(ch) { case 1: { cout<<"enter value to be pushed:"<<endl; cin>>val; push(val); 22 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING break; } case 2: { pop(); break;} case 3: { display(); break; } case 4: { cout<<"exit"<<endl; break; } default: { cout<<"invalid choice"<<endl; } } }while(ch!=4); return 0; } EXPERIMENTAL PROCEDURE: After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: 23 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CONCLUSION: PUSH & POP operations have been successfully implemented in stack ADT using array. EXPERIMENT-6 AIM: Write a program to convert an infix expression to a postfix expression using stacks. OBJECTIVE: To understand the process of conversion of infix expression to postfix expression as an application of stacks PREREQUISITES: Infix, Prefix & Postfix Expressions. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: 24 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: INFIX notations are not as simple as they seem specially while evaluating them. To evaluate an infix expression we need to consider operators’ priority and associative property. e.g. Expression 3+5*4 evaluate to 32 i.e. (3+5)*4 OR to 23 i.e. 3+(5*4). To solve this, problem precedence or priority of the operators was defined. Operator precedence governs evaluation order. An operator with higher precedence is applied before an operator with lower precedence Postfix and prefix expression forms do not rely on operator priorities, a tie breaker, or delimiters. Both prefix and postfix notations have an advantage over infix that while evaluating an expression in prefix or postfix form, we need not consider the priority and associative property (order of brackets). e.g. x/y*z becomes */xyz in prefix and xy/z* in postfix. Both prefix and postfix notations make expression evaluation a lot easier. So it is easier to evaluate expressions that are in these forms. ALGORITHM : Given an expression in the infix form. Create and initialize a stack to hold operators. Print operands as they arrive. If the stack is empty or contains a left parenthesis on top, push the incoming operator onto the stack. If the incoming symbol is a left parenthesis, push it on the stack. If the incoming symbol is a right parenthesis, pop the stack and print the operators until you see a left parenthesis. Discard the pair of parentheses. If the incoming symbol has higher precedence than the top of the stack, push it on the stack. 25 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING If the incoming symbol has equal precedence with the top of the stack, use association. If the association is left to right, pop and print the top of the stack and then push the incoming operator. If the association is right to left, push the incoming operator. If the incoming symbol has lower precedence than the symbol on the top of the stack, pop the stack and print the top operator. Then test the incoming operator against the new top of stack. At the end of the expression, pop and print all operators on the stack. (No parentheses should remain.) SOURCE CODE: #include<iostream> #include<stack> using namespace std; void Postfix(char *exp) { stack <char> s; char output[50],t; for(int i=0;exp[i]!='\0';i++) { char ch = exp[i]; switch(ch) { case '^': case '-': case '+': case '/': case '*': s.push(ch); break; 26 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING case ')': t=s.top(); s.pop(); cout<<t; break; } if (isalpha(ch)) cout<<ch; } } int main( ) { char exp[ ] = "a+b*(c^d-e)^(f+g*h)-i"; cout<<”\n CONVERTED POSTFIX EXPRESSION=”; Postfix(exp); return 0; } EXPERIMENTAL PROCEDURE: After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: 27 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING CONCLUSION: The given infix expression has been successfully converted into postfix expression using stack. EXPERIMENT-7 AIM: Write a program to evaluate a postfix expression using stacks. 28 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING OBJECTIVE: To understand the process of evaluation of postfix expression as an application of stacks. PREREQUISITES: Infix, Prefix & Postfix Expressions. RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are evaluated faster compared to infix notation as parenthesis are not required in postfix. The compiler finds it convenient to evaluate an expression in its postfix form. Postfix form include elimination of parentheses which signify priority of evaluation and the elimination of the need to observe rules of hierarchy, precedence and associativity during evaluation of the expression. Evaluation rule of a Postfix Expression: 1) While reading the expression from left to right, push the element in the stack if it is an operand. 2) Pop the two operands from the stack, if the element is an operator and then evaluate it. 3) Push back the result of the evaluation. Repeat it till the end of the expression. ALGORITHM: 1) Add “)” to postfix expression. 2) Read postfix expression Left to Right until ) encountered 3) If operand is encountered, push it onto Stack [End If] 4) If operator is encountered, Pop two elements i) A -> Top element 29 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING ii) B-> Next to Top element iii) Evaluate B operator A push B operator A onto Stack 5) Set result = pop 6) END SOURCE CODE: #include <iostream> #include <stack> using namespace std; // Function to evaluate given postfix expression int postfixEval(string exp) { // create an empty stack stack<int> stack; // traverse the given expression for (int i = 0; i < exp.length(); i++) { // if current char is an operand, push it to the stack if (exp[i] >= '0' && exp[i] <= '9') { stack.push(exp[i] - '0'); } // if current char is an operator else { // pop top two elements from the stack int x = stack.top(); stack.pop() 30 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING int y = stack.top(); stack.pop(); // evaluate the expression x op y, and push the // result back to the stack if (exp[i] == '+') stack.push(y + x); else if (exp[i] == '-') stack.push(y - x); else if (exp[i] == '*') stack.push(y * x); else if (exp[i] == '/') stack.push(y / x); } } // At this point, the stack is left with only one element // i.e. expression result return stack.top(); } int main() { char exp[20]; char *e; cout<< "\n enter postfix Expression: ="; cin>> exp; e = exp; cout << postfixEval(e); return 0; } 31 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENTAL PROCEDURE: After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: CONCLUSION: Postfix expression has been successfully implemented using stacks. 32 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING EXPERIMENT-8 AIM: Write a recursive function for Tower of Hanoi problem. OBJECTIVE: To learn how to write recursive programs for complex iterative problems PREREQUISITES: Concept and Usage of recursion using stacks RESOURCE/ EXPERIMENTAL SET-UP/EQUIPMENT/APPARATUS/TOOLS: Linux OS or Windows 8/10 Operating System C/C++,Turbo C or gcc compiler in linux THEORY AND APPLICATION: Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings is as depicted – These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over the larger one. There are other variations of the puzzle where the number of disks increase, but the tower count remains the same. Rules: The mission is to move all the disks to some another tower without violating the sequence of arrangement. A few rules to be followed for Tower of Hanoi are − 33 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING * Only one disk can be moved among the towers at any given time. * Only the "top" disk can be removed. * No large disk can sit over a small disk. ALGORITHM: A recursive algorithm for Tower of Hanoi can be driven as follows − START Procedure Hanoi(disk, source, dest, aux) IF disk == 1, THEN move disk from source to dest ELSE Hanoi(disk - 1, source, aux, dest) // Step 1 move disk from source to dest // Step 2 Hanoi(disk - 1, aux, dest, source) // Step 3 END IF END Procedure STOP A skeletal recursive procedure (Outline) for the solution of the problem for N number of disks is as follows: 1. Move the top N-1 disks from peg A to peg B (using C as an auxiliarypeg) 2. Move the bottom disk from peg A to peg C 3. Move N-1 disks from Peg B to Peg C (using Peg A as an auxiliary peg) 4. SOURCE CODE: #include <iostream> 34 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING using namespace std; void toh(int ,char,char,char); int main() { char a,b,c; int x; a='A'; //Start disc b='B'; //Auxillary disc c='C'; //End Disc cout<<"Enter No. of discs:"; cin>>x; toh(x,a,c,b); return 0; } void toh(int x,char a ,char c,char b) { if(x==1) { cout<<"Move the disc 1 from "<<a<<" to "<<c<<endl; //only disc remaining x=x-1; } else { toh(x-1,a,b,c) ; //Moving n-1 poles to auxillary pole cout<<"Move the disc "<<x<<" from"<<a<<" to "<<c<<endl; toh(x-1,b,c,a); // Move n-1 poles to destination } } EXPERIMENTAL PROCEDURE: 35 Roll no. 1915037 Name – ANIKET THAKUR CGC,FACULTY OF ENGINEERING JHANJERI, MOHALI – 140307 DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING After writing the source code, compile the program by selecting Build option from menu bar or by pressing Ctrl-F9 keys together. If there are no errors detected in the program & object file (.obj) has been created successfully, then execute the program by pressing Ctrl-F10 keys together. OUTPUT: CONCLUSION: Recursive solution to puzzle problem “Tower of Hanoi” has been studied & implemented successfully using stacks. 36 Roll no. 1915037 Name – ANIKET THAKUR