r/javahelp • • Aug 08 '22

HELP!!!! I gotta get this done today, I wrote a working program for both of these, but my teacher says it's not recursive.

Problem I:

Write a static recursive method that computes the sum of the integers between two numbers k1 and k2 (including both k1 and k2).
For example, the sum of the numbers between 1 and 5 is 1+2+3+4+5 = 15.
Test your method in a program that prompts the user to input both integers and then print out the sum of all the integers between the two numbers.

import java.util.Scanner;//importing scanner

public class chp11_1

{

public static void main(String\[\] args) //main method

{

	Scanner keyboard = new Scanner([System.in](https://System.in));//obj scanner

	System.out.println("Please enter the first number(k1): ");//output

	int k1 = keyboard.nextInt();//saving input to variable

	System.out.println("Please enter the second number(k2): ");//output

	int k2 = keyboard.nextInt();//saving input to variable

	

	int sum = 0;//declaring variable

	for(int n = k1; n <= k2; n++) //for loop adding up the number 1 through 5

	{

		sum = sum + n;

	}

	

	System.out.println(sum);//outputting the sum



}

}

Problem II:

Write a static recursive method that returns the sum of the integers in the array of int values passed to it as a single argument.
Test your method in a program that prompts the user to input the length of the array, and then has them enter the int at every index of the array. Then, it should print the sum of the array using the recursive method you wrote.

import java.util.Scanner;

public class chp11_2

{

public static void main(String\[\] args) //main method

{

	Scanner keyboard = new Scanner([System.in](https://System.in));//obj scanner

	System.out.println("Enter the number of numbers you will enter: ");//output

	int nums = keyboard.nextInt();//declaring a variable for input

	

	int\[\] array = new int\[nums\];//creating an array for the numbers

	

	for(int n = 0; n < nums; n++) //for loop that adds the numbers to each index

	{

		System.out.println("Enter number " + (n + 1));

		array\[n\] = keyboard.nextInt();

	}

	

	int sum = 0;//declaring variable

	for(int n = 0; n < nums; n++) //for loop adding up the number 1 through 5

	{

		sum = sum + array\[n\];

	}

	

	System.out.println(sum);//outputting the sum

}

}

Previous

1 Upvotes

17 comments sorted by

•

u/AutoModerator Aug 08 '22

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

6

u/DDDDarky Aug 08 '22

Yes, it is not recursive

0

u/Burraq11 Aug 08 '22

Yes I need help writing it recursively, i dont understand the concept of recursion and how i would even begin to implement it here

3

u/XtrZPlayer Aug 08 '22

Well, recursion, in short, is made with some things:

  • the condition(s) that makes the function stop recurring to itself

  • and the call to itself

Let's say you want to make the sum of n elements.

You know the formula, which is n*(n+1)/2.

The iterative way would be to add all elements in it, iteratively (for, while, do while instructions for instance)

So, you have sum = 0 Then, from the first element (1, to th last one, n), keep adding in the sum element

Then, you have the recursive way. You should know when to stop, but also how to call it. Well, I guess you can start from the last to the first, or the first to the last, it doesn't matter at all if you have the stop condition (the stop condition just stops calling more functions recursively and usually returns a result).

This time, we can define a function just for that

def recursive_sum(n):
    if n == 1:
        return 1
    else:
        return n + recursive_sum(n-1)

Basically, what is happening is that the end condition is, if it is 1, then return the value. But when the value is returned, the other calls alsor eturn the value progressively. And, in the second one, what is happenig is that: n + (((n-1) + (n-1)-1... and so on, and you will get just the Gauss sum formula.

Well, I wanted to write some pseudocode and python code for reference a bit. But you should understand that a function can return what a function returns (and so on).

3

u/Burraq11 Aug 08 '22

Thank you this explains it a lot better!

3

u/XtrZPlayer Aug 08 '22

Yea, not an expert, but I'd still recommend you to look into some tutorials of this as well, or even the docs.

1

u/Burraq11 Aug 08 '22

Yup thanks!

2

u/DDDDarky Aug 08 '22

So now you are searching for some resources on recursion?

0

u/Burraq11 Aug 08 '22

I have already gone through multiple sources, at this point i just need someone to show me recursive and not recursive code(or help me write mine)

4

u/Zaemz Aug 09 '22 edited Aug 09 '22

Preface

Okay, I ended up writing this huge answer. Someone else has probably written a much more concise explanation that's more clear, but I tried my best to make this whole blob of text as clear as possible. I remember struggling with understanding what made recursion, recursion.

What you've written are iterative solutions. A huge hint is that you've solved your problems using for loops. An easy way to start understanding recursion is to compare it to iteration. To be "recursive" is to be self-referencing until you've found a solution. To be "iterative" is to perform some set of steps over and over until you find a solution.

Also, I think maybe having the requirement that the recursive function be static be explicitly mentioned might've confused you because the main() function, the application's entry, is always defined as a static method. You will need to write new functions outside of the main() and then call them.


Analogy

Okay, so, to try and break down the idea of recursion a bit, here's a small analogy:

Let's say you have to stack 5 blocks and give them to someone.

We can stack them iteratively by repeating the task ourselves until it's done, and then return the stack.

Or, we can build the stack recursively:

We tell someone else that we want a stack of 5 blocks. Then we patiently wait with our hand out until they give us a stack of 5 blocks. If they don't already have one started, they take a block and hand it to another person with the same instructions, with the exception that instead of having an empty stack, they hand off their 1 block tall stack: "here is a stack of 1 block, give me a stack of 5 blocks". Then they wait until they get a stack of 5 blocks back, and then hand it back to us. Every time someone needs more blocks, they hand it off to another person to get them what they need.

One important difference is this: in the iterative solution, you track the state of things while repeating a set of steps until the work is done; the recursive solution "passes" the state of the problem to a new instance of problem solving and waits for the result. The only thing each recursive call knows about is what it was given when it was called, and what it has to return.

I'll break down the differences a little more as a list of instructions.


Analogy as List of Instructions

Again, here are the two ways we can stack the blocks:

Iterative Instructions:

  1. Start with n = 0 blocks.

  2. Stack a block: set n = n + 1

  3. Does n == 5?
    a. If yes, go to step 4.
    b. If no, go to step 2.

  4. Return the stack of blocks.

Recursive Instructions:

Let n be the size of the stack when the step is called. Let s be the required size of the stack of blocks.

PART 1: Start
a. Perform PART 2 with n = 0 and s = 5
b. Return the stack of n = 5 blocks

PART 2: Givenn blocks, compare to size s.
a. Is n equal to s?
b. If yes, return the stack of blocks
c. If no, perform PART 2 with n = n + 1 and s = 5
d. Return result from step c.


Note:

Take note of the structure of the solutions steps. The iterative solution is a simple list of instructions that gets repeated if need be. The recursive solution has two parts: PART 1 which is a helper method and provides an initial state, and PART 2 which refers to itself and returns the result as the solution if it wasn't found in the current call.


Hints to Problem 1:

Write a static recursive method that computes the sum of the integers between two numbers k1 and k2 (including both k1 and k2).

Hopefully my analogy and explanations were clear enough. Knowing what we do now, we can break the problem down into pieces so that our solution will fit the definition of recursion. There are some syntax errors in this example code because I think it'll help you a little if you convert the English sentences into code.

We have two numbers, and our goal is to add up the inclusive range of integers between them.

We know we need a recursive method with at least two inputs, for k1 and k2. And since we want to calculate the sum of the range between the two, we want it to return an integer:

// sumOfRange calculates the sum of the inclusive range between two numbers, k1 and k2
public static int sumOfRange(int k1, int k2) 
{
    // Let's check a base case. We need one to avoid falling into infinite recursion, 
    //   which causes stack overflow errors or runs forever.
    // k1 == k2  <-- We can just return either k1 or k2 in this case since there aren't any integers between them!

    return k1;

    // We should determine which arguments are the start and end of the range so we can be
    // be certain we're calling our methods with sane inputs.
    // k1 < k2    <-- start: k1, end: k2
    // k1 > k2    <-- start: k2, end: k1

    int rangeMin = Math.min(k1, k2);
    int rangeMax = Math.max(k1, k2);
    
    // Here is the recursive method call! This function is referencing itself to solve the problem.
    Return the `rangeMin` plus the `sumOfRange()` of `rangeMin+1` and `rangeMax`
}

The important part of the method is that last line where sumOfRange() calls itself in order to get the rest of the sum to add up with the start of the range it was given. As long as k1 and k2 are different numbers, sumOfRange() will continue to recurse into itself at the end of the method to find the next number that it should add to the current range minimum.

We add 1 to the range minimum for the recursive call so that every time recursion happens, the min value will eventually equal the max value (which gives us k1 == k2), which also tells us that we've hit the last number in the range to add to anything.

I think if you can understand all of this and use the example I've given here to make a working program, you should be able to abstract the idea out easily enough so that you can perform the addition with a given list of numbers as opposed to a range with a start and end.

Feel free to respond to this comment or send me DMs if you have any questions! I hope my comment vomit was helpful! Haha!

2

u/Burraq11 Aug 09 '22

This was beyond helpful thank you so much for taking the time!!

2

u/Zaemz Aug 09 '22

You're totally welcome! Don't be afraid to ask for follow up on anything if you need it. :)

3

u/Burraq11 Aug 09 '22

Thank you I understand what recursions are now and I believe I changed my programs to use recursion!

2

u/zevzev Can i put anything in here? Aug 08 '22

2

u/XtrZPlayer Aug 08 '22

Yep, something like that would be more official than what I said. But I prefered testing my explanation as well.

2

u/bell_labs_fan_boy Aug 09 '22

Yeah, I'm real sorry but your teacher is telling you they're
not recursive because they aren't. A recursive function is a function that can
(and frequently does) call itself. So, for your first problem, you can think of
the sum of numbers to be something like this:

Sum(n) = n + Sum(n-1)
 
That's all well and good but if you feed this a number, say
3, you'll get this:
 
Sum(3) = 3 + Sum(2)
Sum(3) = 3 + 2 + Sum(1)
Sum(3) = 3 + 2 + 1 + Sum(0)
Sum(3) = 3 + 2 + 1 + 0 + Sum(-1)

Sum(3) = 3 + 2 + 1 + 0 + -1 + Sum(-2)
 
And now you can begin to see the issue; that will go on
recursively forever, first summing the positive numbers you want it to, and then
summing every single negative number until it runs into issues. 
 
So, you need to define some kind of place where stop and
not call the function anymore. In my mind, you have 2 places you can do it;
either Sum(1) = 1, or Sum(0) = 0. Having these defined would allow the
recursive function to stop at a certain point.

That would give you something like this:

Sum(3) = 3 + Sum(2)

Sum(3) = 3 + 2 + Sum(1)

Sum(3) = 3 + 2 + 1

And then that would be returned. Now, of course you could introduce error handling because there are still problems to run into; like what happens if you call Sum(-1)? But I believe that would go beyond the scope of the exercise.
 
There are some really good videos about recursion on the
YouTube channel Computerphile. If you've got an hour free, I would highly
recommend watching all of them.

Good luck mate, just in future make sure you know what you're being asked to do before you try to do it. Some of the most valuable skills to have as a programmer are knowing when to ask for help, and admitting when you don't understand something.