Write a program to take a string as input and output its reverse.
Write the program in java.
Answers
Answer:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a string: ");
char[] letters = scanner.nextLine().toCharArray();
System.out.print("Reverse string: ");
for (int i = letters.length - 1; i >= 0; i--) {
System.out.print(letters[i]);
}
System.out.print("\n");
}
}
Explanation:
Answer:
Using Java, the code goes like -
import java.util.*;
public class Reverse_String {
public static void main(String args[]) {
System.out.print("Enter a String: ");
String original_string,reversed_string="";
original_string=(new Scanner(System.in)).nextLine();
for(int i=original_string.length()-1;i>=0;i--)
reversed_string+=original_string.charAt(i);
System.out.println("Original String: "+original_string);
System.out.println("Reversed String: "+reversed_string);
}
}
Logic:
Logic is very easy. Consider a string - "Hello"
Length of string = 5
Now, let us write the index of each character in the string. Note that index value starts with 0.
So, index value range is - (0 to length(string) - 1)
- Here, a loop is created that iterates in the range i > length(original_string) - 1 to 0 so as to access the characters present in the string from last to first.
- To calculate the length of string, the length() function is used and to access the character at specific index, the charAt() function is used.
- Using charAt() function, we will access the characters present in the string from backwards and concatenate them. The resultant string is the reversed one of the original.
See the attachment.