Created
April 7, 2022 15:10
-
-
Save aadipoddar/9792e8839b2306c7819a41528ba79697 to your computer and use it in GitHub Desktop.
Count The Number of words in the Sentence using Recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a program to accept a sentence | |
and the number of words in the sentence. | |
INPUT: Kolkata is a nice City | |
OUTPUT: Number of Words: 5 | |
*/ | |
import java.util.Scanner; | |
class WordsCountRecursion { | |
int wordsCount(String sentence, int i) { | |
if (i == sentence.length()) | |
return 0; | |
if (sentence.charAt(i) == ' ') | |
return 1 + wordsCount(sentence, i + 1); | |
return wordsCount(sentence, i + 1); | |
} | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
WordsCountRecursion wcr = new WordsCountRecursion(); | |
System.out.println("Enter a sentence: "); | |
System.out.println("Number of words: " + wcr.wordsCount(sc.nextLine() + " ", 0)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment