InterviewSolution
| 1. |
A register is an entity which can hold a maximum of 100 names. The register enables the user to add and remove names from the topmost end only. Define a class Register with the following details: Class name: Register Data members/instance variables: stud[]: array to store the names of the students cap: stores the maximum capacity of the array to point the index of the top end top: to point the index of the top end Member functions: Register (int max) : constructor to initialize the data member cap = max, top = -1 and create the string array void push(String n): to add names in the register at the top location if possible, otherwise display the message “OVERFLOW” String pop(): removes and returns the names from the topmost location of the register if any, else returns “$$” void display (): displays all the names in the register (a) Specify the class Register giving details of the functions void push(String) and String pop(). Assume that the other functions have been defined. The main function and algorithm need NOT be written. (b) Name the entity used in the above data structure arrangement. |
|
Answer» (a) import java.io.*; import java.util.Scanner; class Register{ private String stud[]; private int cap; private int top; public Register(int max) { top = -1; cap = max; if(cap > 100) cap = 100; stud = new String[cap]; } public void push(String n) { if(top + 1 < cap) stud[++top] = n; else System.out.println(“OVERFLOW”); } public String pop() { if(top == -1) return “$$”; else return stud[top--]; } public void display() { if(top== -1) System.out.println(“Register empty.”); else { System.out.println(“StudentList:”); for(int i = 0; i <= top; i++) System.out.println(stud[i]); } } public static void main(String args[ ]) throws IOException { Scanner sc = new Scanner(System.in); System. out.print(“Maximum size: ”); int max = sc.nextlnt(); Register obj = new Register(max); while(true) { System.out.println(“1. Push”); System.out. println(“2. Pop”); System.out.println(“3. Display”); System.out.print(“Enter your choice: ”); int choice = sc.nextlnt(); switch(choice) { case 1: System.out.print(“Student Name: ”); String n = sc.next(); obj.push(n); break; case 2: n = obj.pop(); if(n.equals(“$$”)) System.out.println(“UNDERFLOW!”); else System.out.println(n + “popped.”); break; case 3: obj.display(); break; default: System.out.println(“Exiting...”); return; } } } } (b) The entity used in the above data structure is stack. Stack works upon the principle of LIFO i. e., Last In First Out. |
|