Stack Program ISC Computer Science 2014 Theory

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().
void 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 giving details of all the functions.

import java.util.Scanner;
class ArrayToStack{
    int m[];
    int st[];
    int cap;
    int top;
    public ArrayToStack(int n){
        if(n > 50)
            n = 50;
        cap = n;
        top = -1;
        m = new int[cap];
        st = new int[cap];
    }
    public void inputMarks(){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter " + cap + " numbers:");
        for(int i = 0; i < cap; i++){
            m[i] = Integer.parseInt(in.nextLine());
            pushMarks(m[i]);
        }
        for(int i = 0; i < m.length; i++){
            for(int j = 0; j < m.length - 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 == cap - 1)
            System.out.println("not possible");
        else
            st[++top] = v;
    }
    public int popMarks(){
        if(top == -1)
            return -999;
        return st[top--];
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory