ISC practical papers › ISC 2013 › Question 3
Display & Count Palindromic Words
ISC 2013 Computer Science Practical, Question 3 · Strings
The question
A palindrome is a word that may be read the same way in either direction. Accept a sentence in UPPER CASE which is terminated by either “.”, “?”, or “!”. Each word of the sentence is separated by a single blank space.
Perform the following tasks: a) display the count of palindromic words in the sentence. b) Display the palindromic words in the sentence.
Example of palindromic words:
MADAM, ARORA, NOON
Test your program with the sample data and some random data:
Example 1
INPUT: MOM AND DAD ARE COMING AT NOON.
OUTPUT: MOM DAD NOON
NUMBER OF PALINDROMIC WORDS: 3
Example 2
INPUT: NITIN ARORA USES LIRIL SOAP.
OUTPUT: NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS: 3
Example 3 INPUT: HOW ARE YOU? OUTPUT: NO PALINDROMIC WORDS
Question: ISC 2013 Computer Science Paper 2 (Practical), Question 3, set by the Council for the Indian School Certificate Examinations (CISCE). Solution and video: Vinay Singh.
Java solution
import java.util.*;
class Palindrome {
private String sentence, answer;
private int frequency;
public Palindrome(String sentence) {
this.sentence = sentence;
frequency = 0;
answer = "";
process();
}
private boolean isPalindrome(String word) {
int half = word.length() / 2;
for (int position = 0; position < half; position++) {
if (word.charAt(position) != word.charAt(word.length() - 1 - position))
return false;
}
return true;
}
private void process(){
char ch;
String delimters=".?! ",word="";
for( int position=0; position<sentence.length();position++){
ch = sentence.charAt(position);
if(delimters.indexOf(ch)>=0){
if(isPalindrome(word)){
answer+=word+" ";
frequency++;
}
word="";
}else{
word+=ch;
}
}
}
public int getFrequency(){
return frequency;
}
public String toString(){
return answer.trim();
}
}
public class ISC2013Q3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("INPUT:\t");
String sentence = in.nextLine();
Palindrome objPalindrome = new Palindrome(sentence);
System.out.print("OUTPUT:\t");
if(objPalindrome.getFrequency()>0){
System.out.println(objPalindrome);
System.out.println("\tNUMBER OF PALINDROMIC WORDS: "+objPalindrome.getFrequency());
}else{
System.out.println("NO PALINDROMIC WORDS");
}
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.