Skip to content

Instantly share code, notes, and snippets.

@aadipoddar
Created April 7, 2022 15:10
Show Gist options
  • Save aadipoddar/9792e8839b2306c7819a41528ba79697 to your computer and use it in GitHub Desktop.
Save aadipoddar/9792e8839b2306c7819a41528ba79697 to your computer and use it in GitHub Desktop.
Count The Number of words in the Sentence using Recursion.
/*
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