Array to Stack ISC 2014 Theory

A stack is a linear data structure which enables the user to add and remove integers from one end only, using the concept of LIFO (Last In First Out). An array containing the marks of 50 students in ascending order is to be pushed into the stack.

Define a class ArrayToStack with the following details:
Class name: ArrayToStack
Data members/instance variables:
m[]: to store the marks.
st[]: to store the stack elements.
cap: maximum capacity of the array and stack.
top: to point the index of the topmost element of the stack.
Methods/Member functions:
ArrayToStack(int n): parameterized constructor to initialize cap = n and top = -1.
void inputMarks(): to input the marks from user and store it in the array m[] in ascending order and simultaneously push the marks into the stack st[] by invoking the function pushMarks().
int pushMarks(int v): to push the marks into the stack at top location if possible, otherwise, display “not possible”
int popMarks(): to return marks from the stack if possible, otherwise, return -999.
void display(): to display the stack elements.

Specify the class ArrayToStack, giving the details of the constructor, void inputMarks(), void pushMarks(int), int popMarks() and void display().

The main() function and the algorithm need not be written.

import java.io.*;
class ArrayToStack{
    private int m[];
    private int st[];
    private int cap;
    private int top;
    public ArrayToStack(int n){
        cap = n;
        top = -1;
        m = new int[cap];
        st = new int[cap];
    }
    public void inputMarks()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input marks:");
        for(int i = 0; i < cap; i++){
            m[i] = Integer.parseInt(br.readLine());
            pushMarks(m[i]);
        }
        for(int i = 0; i < cap; i++){
            for(int j = 0; j < cap - 1 - i; j++){
                if(m[j] > m[j + 1]){
                    int temp = m[j];
                    m[j] = m[j + 1];
                    m[j + 1] = temp;
                }
            }
        }
    }
    public void pushMarks(int v){
        if(top + 1 < cap)
            st[++top] = v;
        else
            System.out.println("not possible");
    }
    public int popMarks(){
        if(top == -1)
            return -999;
        else
            return st[top--];
    }
    public void display(){
        for(int i = 0; i <= top; i++)
            System.out.print(st[i] + "\t");
        System.out.println();
    }
}

Leave a Reply

%d bloggers like this: