1 ) Write a recursive method called descend that prints the numbers 1…n in desce
ID: 3929390 • Letter: 1
Question
1 ) Write a recursive method called descend that prints the numbers 1…n in descending order. Your main method will need to read n from the user, then call method descend with the number read.
2) Write a recursive method called exp to perform exponentiation return x, assuming n >= 0. Your main method will need to read x and n from a file, then call method exp with the input read. Print the result of x after each recursive call.
This is what i have so far. I just dont get part 2.
import java.util.Scanner;
public class Recursion {
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int n = 0;
System.out.println("Enter Number");
n = scn.nextInt();
descend(n);
}
public static int descend(int n){
if(n==0){
return n;
}
else{
System.out.println(n);
descend(n-1);}
return n;
}
Explanation / Answer
// include the required header file
import java.util.*;
import java.io.*;
public class Recursion {
public static void main(String[] args){
int x,n;
BufferedReader br = null;
try {
String sCurrentLine;
//read first line frm file
br = new BufferedReader(new FileReader("input.txt"));
while ((sCurrentLine = br.readLine()) != null) {
//spilt the line read using "^" as tokenizer
String tokens[]=sCurrentLine.split(" ");
//store first token as x(base)
x=Integer.parseInt(tokens[0]);
//store second token as n(power)
n=Integer.parseInt(tokens[1]);
//call exp function
System.out.println(x+"^"+n+" : "+exp(x,n));
}
} catch (IOException e) {
System.out.println("Unable to able file!!");
}
}
//fiunction to calculate exp
public static int exp(int base, int power)
{
//return 1 if power is 0
if(power==0)
{
return 1;
}
//else multiply base with power
else
{
int result=base*exp(base, power-1);
System.out.println(result);
return result;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.