Code with Vinay

ISC practical papers › ISC 2012 › Question 2

Sort words in alphabetical order

ISC 2012 Computer Science Practical, Question 2 · Strings

The question

Write a program to accept a sentence as input.
The words in the string are to be separated by a blank.
Each word must be in upper case.
The sentence is terminated by either “.”,”!” or “?”.

Perform the following tasks: (i) Obtain the length of the sentence (measured in words). (ii) Arrange the sentence in alphabetical order of the words.

Test your program with the sample data and some random data:

Example 1
INPUT:
    NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
    LENGTH : 6
    REARRANGED SENTENCE
    INVENTION IS MOTHER NECESSITY OF THE
Example 2
INPUT:
    BE GOOD TO OTHERS.
OUTPUT:
    LENGTH : 4
    REARRANGED SENTENCE
    BE GOOD OTHERS TO

Question: ISC 2012 Computer Science Paper 2 (Practical), Question 2, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.

Java solution

ISC2012Q2.java Download GitHub
import java.util.*;
class Sentence{
    private String sentence,output;
    private int length;
    public Sentence(String sentence){
        this.sentence=sentence.substring(0, sentence.length()-1);
        process();
    }
    private void process(){
        String word[] = sentence.split(" ");
        length=word.length;
        sort(word);
        output="";
        for( String w:word){
            output+=w+" ";
        }
        output=output.trim();
    }
    private void sort(String word[]){
        String temp;
        boolean swapped;
        for( int pass=0; pass<word.length-1;pass++){
            swapped=false;
            for( int pos=0; pos<word.length-1-pass;pos++){
                if(word[pos+1].compareTo(word[pos])<0){
                    temp=word[pos+1];
                    word[pos+1]=word[pos];
                    word[pos]=temp;
                    swapped=true;
                }
            }
            if(!swapped) break;
        }
    }
    public int getLength(){
        return length;
    }
    public String toString(){
        return output;
    }
}
public class ISC2012Q2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("INPUT:\n\t");
        String sentence = in.nextLine();
        Sentence obj = new Sentence(sentence);
        System.out.println("OUTPUT:\n\tLENGTH IS: "+obj.getLength());
        System.out.println("\tREARRANGED SENTENCE");
        System.out.println("\t"+obj);
        in.close();
    }
}

All these solutions in one free book

Pragmatic Solutions to ISC Computer Science Practical Problems collects every program from 2004 to 2021 in a 202-page PDF.

Get the free PDF ₹0 ISC 2027 mock papers