Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Instead of diving headfirst into recursion, let us first get our feet wet. Let u

ID: 3774629 • Letter: I

Question

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 (l)=l sumn (2)=l+2=3 sumn (3)=l+2+3=6... Part A] 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(l)=l sumn_r(2)=2+sumn_r(l) sumn _r(3)=3+sumn_r(2) and furthermore sumn _r(n)=n+ sumn _r(n-l) Use the above relation to define the sumn _r function recursively.

Explanation / Answer

import java.util.Scanner;

public class HelloWorld{
public static int sum(int n){
int sum=0;
for(int i=1;i<=n;i++)//loop till n
sum=sum+i; //calculating sum
return sum; //returning sum
}

//using recursion
public static int sumn_r(int n){
if(n != 0) //if n is not equal to zero
return n + sumn_r(n-1);//using recursion
else
return n;
}   
public static void main(String []args){
int n;//for storing user entered value
Scanner input=new Scanner(System.in);
System.out.println("Enter n upto which you want to sum the integers :");
n=input.nextInt();
//without using recursion
System.out.println("Sum calculated without using the recursion :"+sum(n));
//using recursion
System.out.println("Sum calculated using the recursion :"+sumn_r(n));
  
}
}

/******OUTPUT*******
Enter n upto which you want to sum the integers :   
5   
Sum calculated without using the recursion :15   
Sum calculated using the recursion :15
******OUTPUT*******/
/* This code has been tested on eclipse Please do ask in case of any doubt thanks. */