Question

using javaGaurav Bhardwaj 1992584 FCCR (3).docx (Protected View) - Word (Unlicensed Product) Review View Help Tell me what you want to

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Using for loop :

Code Snippet :

Output :

Raw Code :

import java.util.*; //Importing necessary packages
public class rev_words_for{
   public static void main(String[] args) { //main method
       Scanner sc = new Scanner(System.in); //Creation of Scanner object
       String str = sc.nextLine(); //Reading line from console
       String[] arr = str.split(" "); //Converting the string to String Array using delimiter space " "
       for(int i = arr.length- 1;i>=0;i--){ //Iterating from arr.length - 1 to 0 as we need to reverse words
           System.out.print(arr[i] + " "); //Printing words space in between them
       }
       System.out.println(); //New line
   }
}

Using while loop :

Code Snippet :

Output :

Raw Code :

import java.util.*; //Importing necessary packages
public class rev_array_while{
   public static void main(String[] args) { //main method
       Scanner sc = new Scanner(System.in); //Creation of Scanner object
       String str = sc.nextLine(); //Reading line from console
       String[] arr = str.split(" "); //Converting the string to String Array using delimiter space " "
       int i = arr.length-1; //Indexing starts from 0 as we need to iterate from backwards the last index is arr.length - 1
       while(i>=0){ //Iterate until i is greater than or equal to 0
           System.out.print(arr[i] + " "); //printing words with space in between
           i--; //Decrement i
       }
       System.out.println(); //printing new line
   }
}

Please do vote. :)

Add a comment
Know the answer?
Add Answer to:
using java Gaurav Bhardwaj 1992584 FCCR (3).docx (Protected View) - Word (Unlicensed Product) Review View Help...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT