USING JAVA:
I was asked to write a function that obtains a name from the user and returns it in reverse order (So if the user inputs "MIKE" the function returns "EKIM"). You can't use string variables it can only be done using a Char Array. Additionally, you can use a temporary Char Array but you are supposed to return the reverse order in the same char array that the user input, this is for hypothetical cost purposes -we are supposed to use as little chars as possible. Below is the code I have so far but I am having trouble coding the temp array and putting the reverse in the same char array as the input comes in:
static char[] reverse(char[] name)
{
int length = name.length;
for(int i = length-1; i>=0; i—)
{
}
return name;
}
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments(read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation please refer code Images
Typed Code:
//importing required package
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Scanner is used to take inputs from the user
Scanner s = new Scanner(System.in);
System.out.print("Enter String: ");
//Character array is used to store Characters
//getting Characters from user
char[] name = s.next().toCharArray();
//calling reverse method and return values store it in char
array
char[] n = reverse(name);
System.out.print("Reverse String: ");
//for loop will iterate length of char array times
for(int i = 0 ; i < n.length; i++)
{
//for every iteration, printing single Character
System.out.print(n[i]);
}
}
//method called
static char[] reverse(char[] name)
{
//taking length as length of char array
int length = name.length;
//initializing j as 0
int j = 0;
//taking temporary char array
char[] temp = new char[length];
//for loop will iterate till length of char array
times
//in reverse order
for(int i = length-1; i>=0; i--)
{
//storing one by one Character to temp char
array
temp[j] = name[i];
//increasing j value
j++;
}
//storing temp to name
name = temp;
//return name
return name;
}
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!
Get Answers For Free
Most questions answered within 1 hours.