Stack Program ISC Computer Science 2022 Semester 2 Theory

A stack is a kind of data structure which can store elements with the restriction that an element can be added or removed from the top end only.

The details of the class Stack is given below:

Class name: Stack

Data members/instance variables:
cha[]: array to hold the characters
size: stores the maximum capacity of the stack
top: to point the index of the topmost element of the stack

Member functions/methods:
Stack(int m): constructor to initialize the data member size = m, top = -1 and create the character array
void pushChar(char v): to add characters from the top end if possible else display the message "Stack full"
char popChar(): to remove and return characters from the top end, if any, else returns '$'
void display(): to display elements of the stack

Specify the class Stack, giving details of void pushChar(char) and char popChar(). Assume that the other functions have ben defined.

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

import java.util.Scanner;
class Stack{
    char cha[];
    int size;
    int top;
    public Stack(int m){
        size = m;
        top = -1;
        cha = new char[size];
    }
    public void pushChar(char v){
        if(top + 1 == size)
            System.out.println("Stack full");
        else
            cha[++top] = v;
    }
    public char popChar(){
        if(top == -1)
            return '$';
        return cha[top--];
    }
    public void display(){
        if(top == -1)
            System.out.println("Stack empty");
        for(int i = 0; i <= top; i++)
            System.out.print(cha[i] + " ");
        System.out.println();
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter stack size: ");
        int m = Integer.parseInt(in.nextLine());
        Stack obj = new Stack(m);
        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 = Integer.parseInt(in.nextLine());
            switch(choice){
            case 1:
                System.out.print("Enter the character: ");
                char v = in.nextLine().charAt(0);
                obj.pushChar(v);
                break;
            case 2:
                v = obj.popChar();
                if(v == '$')
                    System.out.println("Stack empty");
                else
                    System.out.println(v + " popped");
                break;
            case 3:
                obj.display();
                break;
            default:
                System.out.println("Bye!");
                return;
            }
        }
    }
}

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