icse-promo

Question

A palindrome is a word that may be read the same way in either direction.
Accept a sentence in uppercase 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
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					
import java.util.Scanner;
public class palindromeWordsInSentence 
{  
    public static void main(String[] args)
    {  
        String sen="",wd="",wd1="",palindromeWords="";
        char ch=' ',ch1=' ';
        int i=0,len=0,count=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a sentence");   
        sen = sc.nextLine(); 
        sen=sen+" ";
        sen=sen.toLowerCase();
        len=sen.length();

        for(i=0;i< len;i++)
        {
            ch=sen.charAt(i);
            if(ch==' ')
            {
                
                if(wd.equals(wd1)==true)
                {
                    palindromeWords+=wd1+" ";
                    count++;
                }
                wd1="";
                wd="";
                
            }
            else
            {
                wd=wd+ch;
                wd1=ch+wd1;
            }
        }
        if(count>0)
        {
            System.out.println("Palindrome words in sentence:");   
            System.out.println(palindromeWords);   

            System.out.println("NUMBER OF PALINDROMIC WORDS:"+count);
        }
        else
        {
            System.out.println("NO PALINDROMIC WORDS FOUND");
        }
    }  
}    

				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *