USE JAVA FOR THE FOLLOWING 1. (Finding the largest number in an array) Write a r
ID: 664664 • Letter: U
Question
USE JAVA FOR THE FOLLOWING
1. (Finding the largest number in an array) Write a recursive method that returns the largest integer in an array.
2. (Printing the characters in a string reversely) Write a recursive method that displays a string reversely on the console using the following header:
public static void reverseDisplay(String value)
3. (Summing the digits in an integer using recursion) Write a recursive method that computes the sum of the digits in an integer.
4. (String permutation) Write a recursive method to print all the permutations of a string. For example, for a string abc, the printout is:
abc
acb
bac
bca
cab
cba
Hint:
Declare the following two methods. The second is a helper method.
public static void displayPermutation(String s)
public static void displayPermutation(String s1, String s2)
The first method simply invokes displayPermutation("", s). The second method uses a loop to move a character from s2 to s1 and recursively invoke it with a new s1 and s2. The base case is that s2 is empty and prints s1 to the console.
Explanation / Answer
1 class RecursiveMax { public static void main(String[] args) { int[] arr = {10, 5, 7, 9, 15, 6, 11, 8, 12, 2, 3}; int max = recursiveMax(arr, arr.length); System.out.println("Maximum element: " + max); } static int recursiveMax(int[] arr, int length) { if (length == 1) return arr[0]; return max(recursiveMax(arr, length - 1), arr[length - 1]); } private static int max(int n1, int n2) { return n1 > n2 ? n1 : n2; } } import java.io.*; import java.lang.*; import java.util.*; public class RevString { public String reverse(String s, int index ) { if( index>0 ) { return s.charAt( --index) + reverse( s, index); } return ""; } public static void main(String[] args)throws IOException { DataInputStream in=new DataInputStream(System.in); String a;// the given string System.out.println("Enter a String"); a=in.readLine(); RevString obj=new RevString(); int l=a.length(); // calculates Length of String System.out.println(obj.reverse(a,l)); // Pass Parameter as String, Length. } } public class Testing{ @Test public void sumOfDigit(){ assertEquals(6, SumOfDigitSolution.sumOfDigit(123)); assertEquals(46, SumOfDigitSolution.sumOfDigit(Integer.MAX_VALUE)); assertEquals(0, SumOfDigitSolution.sumOfDigit(0)); assertEquals(-6, SumOfDigitSolution.sumOfDigit(-123)); assertEquals(-47, SumOfDigitSolution.sumOfDigit(Integer.MIN_VALUE)); } } public class Permutations { private boolean[] used; private StringBuilder out = new StringBuilder(); private final String in; public Permutations( final String str ){ in = str; used = new boolean[ in.length() ]; } public void permute( ){ if( out.length() == in.length() ){ System.out.println( out ); return; } for( int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.