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

Recursion is a problem solving technique that involves two ingredients. 1. We ne

ID: 3860227 • Letter: R

Question

Recursion is a problem solving technique that involves two ingredients.

1. We need to describe how the problem is when the input is very small (as small as possible), this is known as the base case.

2. The recursive step: incorporate computations involving smaller data to construct your solution.

Practice Exercise: Write a Java recursive method that given a positive integer n calculates:

1^2 + 2^2 + 3^2 +...+ n^2

Note: Can somebody help me with this exercise. It is for intro to computer science. Your help is appreciated.

Explanation / Answer

As given in the problem, Every Recursion Program must have a base case. That means, for that particular case, our program returns value, instead of calling itself again(Recursion). For this problem , finding sum of squares of first n positive integers, base case could be

if(n==1){

return 1

}

So, if n is 1, answer will be 1. If n is not one, we have to go for recursion

if(n!=1)

return n^2 + recurse(n-1);

When n is not 1, then answer will be n^2 + recurse(n-1).

This is the java program :

class Sample2{
  
static int recurse(int n){
//This is the base case
if(n==1){
return 1;
}
//This is recursion
return n*n+recurse(n-1);
}
public static void main(String[] args) {
System.out.println(recurse(10));
}
}

OUTPUT :

385

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote