Submit your answers to the lab instructor once you have completed. Failure to at
ID: 3841681 • Letter: S
Question
Submit your answers to the lab instructor once you have completed. Failure to attend the lab and submit will result in a ZERO FOR THIS LAB. NO EXCEPTIONS. Write a program that calls a RECURSIVE method called write Squares that accepts an integer parameter n. This method prints the squares of the odd numbers separated by commas, in descending order, followed by the squares of even numbers in ascending order. For example, . Write Squares(n) prints the following output: write Squares (9) 81, 49, 25, 9, 1, 4, 16, 36, 64 write Squares(1); 1 write Squares (8) 49, 25, 9, 1, 4, 16, 36, 64 write Squares (4); 9, 1, 4, 16 Write a program that calls a method called Search that performs a sequential search. the method accepts two parameters: an array of integers and an integer n. If it finds "n' it returns the index of n in arr, else it returns -1.Explanation / Answer
Here is the code for you:
class RecursiveSquaresOddEvenSeqSearch
{
public static void writeSquares(int n)
{
if(n % 2 == 0)
writeSquaresHelper(n, n-1);
else
writeSquaresHelper(n, n);
System.out.println();
}
public static void writeSquaresHelper(int n, int x)
{
if(x <= n)
{
System.out.print(x*x + " ");
if(x == 1)
writeSquaresHelper(n, x+1);
else if(x % 2 == 0)
writeSquaresHelper(n, x+2);
else
writeSquaresHelper(n, x-2);
}
}
public static int seqSearch(int[] array, int searchKey)
{
return seqSearchHelper(array, 0, searchKey);
}
public static int seqSearchHelper(int[] array, int index, int searchKey)
{
if(index == array.length)
return -1;
else if(array[index] == searchKey)
return index;
else
return seqSearchHelper(array, index+1, searchKey);
}
public static void main(String[] args)
{
writeSquares(9);
writeSquares(1);
writeSquares(8);
writeSquares(4);
}
}