Word Pile Stack ISC Computer Science 2015 Theory

WordPile is an entity which can hold a maximum of 20 characters. The restriction is that a character can be added or removed from one end only.

Some of the members of the class are given below:

Class name: WordPile

Data members/instance variables:
ch[]: character array to hold the character elements
capacity: integer variable to store the maximum capacity
top: to point to the index of the topmost element

Methods/member functions:
WordPile(int cap): constructor to initialize the data member capacity = cap, top = -1 and create the WordPile
void pushChar(char v): adds the character to the top of WordPile if possible, otherwise output a message "WordPile is full"
char popChar(): returns the deleted character from the top of the WordPile if possible, otherwise it returns '\\'

(a) Specify the class WordPile giving details of the constructor, void pushChar(char) and char popChar(). The main() function and algorithm need not be written.

import java.util.Scanner;
class WordPile{
    char ch[];
    int capacity;
    int top;
    public WordPile(int cap){
        capacity = cap;
        ch = new char[capacity];
        top = -1;
    }
    public void pushChar(char v){
        if(top + 1 == capacity)
            System.out.println("WordPile is full");
        else
            ch[++top] = v;
    }
    public char popChar(){
        if(top == -1)
            return '\\';
        return ch[top--];
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("WordPile capacity: ");
        int cap = Integer.parseInt(in.nextLine());
        WordPile obj = new WordPile(cap);
        while(true){
            System.out.println("1. Push character");
            System.out.println("2. Pop character");
            System.out.print("Enter your choice: ");
            int choice = Integer.parseInt(in.nextLine());
            switch(choice){
            case 1:
                System.out.print("Character to be pushed: ");
                char ch = in.nextLine().charAt(0);
                obj.pushChar(ch);
                break;
            case 2:
                ch = obj.popChar();
                if(ch == '\\')
                    System.out.println("WordPile is empty");
                else
                    System.out.println(ch + " popped");
                break;
            default:
                System.out.println("Bye!");
                return;
            }
        }
    }
}

(b) What is the name of the entity described above and state one of its applications.
Stack is the name of the entity described above. One of its applications is to reverse a string.

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