Using Java... Instead of diving headfirst into recursion, let us first get our f
ID: 3774997 • Letter: U
Question
Using Java...
Instead of diving headfirst into recursion, let us first get our feet wet. Let us try two different ways to write a function to calculate the sum of the first n integers, and we will call it sumn. sumn(1) = 1 sumn (2) = 1 + 2 = 3 sumn (3) = 1 + 2 + 3 = 6... Write a function of the form, int sumn (int n){...} that calculates the above sum by using a for loop. Now use recursion to write another function which calculates the same quantity by using recursion. Call the function sumn_r Note that sumn_r(1) = 1 sumn_r(2) = 2 + sumn_r(1) sumn_r(3) = 3 + sumn_r(2) and furthermore sumn_r(n) = n + sumn_r (n-1) Use the above relation to define the sumn_r function recursively.Explanation / Answer
SumOfN.java
import java.util.Scanner;
public class SumOfN {
int sumn(int n){
int sum =0;
for(int i=1; i<=n ; i++){
sum = sum + i;
}
return sum;
}
int sumn_r(int n){
if(n == 0){
return 0;
}
else{
return n + sumn_r(n-1);
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter n value: ");
int n = scan.nextInt();
SumOfN obj = new SumOfN();
System.out.println("Sum of "+n+" number using non recursive is "+obj.sumn(n));
System.out.println("Sum of "+n+" number using recursive is "+obj.sumn_r(n));
}
}
Output:
Enter n value: 5
Sum of 5 number using non recursive is 15
Sum of 5 number using recursive is 15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.