Computer Science, asked by lepcharenzongcalvin, 6 months ago

write a program in java to enter a sentence and print the largest and the smallest word present using scanner class nd for loop​

Answers

Answered by AnshSharma007
1

Answer:

Here is the program:

public class SmallestLargestWord    

   

  public static void main(String[] args){     

      String string = "Hardships often prepare ordinary people for an extraordinary destiny";    

      String word = "", small = "", large="";    

      String[] words = new String[100];    

      int length = 0;    

          

      //Add extra space after string to get the last word in the given string    

      string = string + " ";    

          

      for(int i = 0; i < string.length(); i++){    

          //Split the string into words    

          if(string.charAt(i) != ' '){    

              word = word + string.charAt(i);    

          }    

          else{    

              //Add word to array words    

              words[length] = word;    

              //Increment length    

              length++;    

              //Make word an empty string    

              word = "";    

          }    

      }            

      //Initialize small and large with first word in the string    

      small = large = words[0];    

          

      //Determine smallest and largest word in the string    

      for(int k = 0; k < length; k++){    

              

          //If length of small is greater than any word present in the string    

          //Store value of word into small    

          if(small.length() > words[k].length())    

              small = words[k];    

   

          //If length of large is less than any word present in the string    

          //Store value of word into large    

          if(large.length() < words[k].length())    

              large = words[k];    

      }    

      System.out.println("Smallest word: " + small);    

      System.out.println("Largest word: " + large);    

  }  }  

Explanation:

Here are the steps:

STEP 1: START

STEP 2: DEFINE String string="Hardships often prepare ordinary people for an extraordinary destiny"

STEP 3: DEFINE word = " ", small = " ", large = " ".

STEP 4: Make object of String[] words.

STEP 5: SET length =0

STEP 6: string = string + " "

STEP 7: SET i=0. REPEAT STEP 8 to 9 STEP UNTIL i

STEP 8: IF(string.charAt(i) != ' ') then

              word =word + string.charAt(i)

              else

              word[length]=word

              length =length + 1

              word = " "

STEP 9: i=i+1

STEP 10: small = large =words[0]

STEP 11: SET k = 0. REPEAT STEP 12 to STEP 14 UNTIL k

STEP 12: IF(small.length() > words[k].length())

              then

              small = words[k]

STEP 13: IF(large.length() < words[k].length())

              then

              large = words[k]

STEP 14: k = k + 1

STEP 15: PRINT small

STEP 16: PRINT large

STEP 17: END

Similar questions