-1

Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.

Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.

Your Output should look like exactly this :

################### output example 1

Enter a number : 96374

I am calculating.....

Step 1 : 9 + 6 + 3 + 7 + 4 = 29

Step 2 : 2 + 9 = 11

Step 3 : 1 + 1 =2

Finally Single digit in 3 steps !!!!!

Your answer is 2.

I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.

package numout;
import java.util.Scanner;
public class NumOut {


   public static void main(String[] args) {
       System.out.print("Enter number: ");
       Scanner scan = new Scanner(System.in);
       int n = scan.nextInt(); 
       System.out.println(n);
   }
   public int sumDigit(int n){
       int sum = n % 9;
       if(sum == 0){
           if(n > 0)
               return 9;
       }
       return sum;
   }    
}

The output understandably duplicates the code given by the input from the user. I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.

jrbedard
  • 3,662
  • 5
  • 30
  • 34
mbish75
  • 21
  • 1
  • 6
  • Check out this explanation of the Fibonacci recursive program written in Java: [Java recursive Fibonacci sequence](http://stackoverflow.com/questions/8965006/java-recursive-fibonacci-sequence). This should give you insight on what you need to do. – Mr. Polywhirl Sep 21 '16 at 01:14
  • This is too vague a question. The only way someone can really answer it is to write the code for you, which I hope they will not do. You need to narrow this down to a specific question about why code is not working the way you expect it to. I suggest that you start by forgetting about recursion and multiple steps -- can you write a program that takes an integer and outputs the sum of its digits? – Dave Costa Sep 21 '16 at 01:18
  • You need to simply return the mod10 of the incoming parameter and add it to the call itself by passing in said parameter divided by 10. Don't forget to check for 0 so that you can return from your function. – Mr. Polywhirl Sep 21 '16 at 01:20
  • Again I am not trying to be vague or get code. Just trying to understand the formatting I guess. I'm not even sure. I totally understand mod 10. mod in general, but that is math. To translate that into the code is where I am getting stuck. Does this get easier with practice/ repetition. It's like a hurdle I am getting stuck on. Are there any only programs that can generate simple scenarios(starting/creating a program) where I would have to solve with code. I feel like that would be a great start. – mbish75 Sep 21 '16 at 01:43

3 Answers3

3

Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.

What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Also, be mindful that a recursive program involves two things: 1. The recursive call (with the parameters needed) 2. A stopping condition (usually the smallest problem) that will stop the subsequent recursive calls. – code4kix Sep 21 '16 at 01:22
  • @Code-Apprentice . Thanks for this verbal input it helps out more than you would think. For my intellectual well being what path would I follow to create same program without recursion or loop (for/ while). Again I can see we need a base case and then use mode 10 but I am at a loss from there on. – mbish75 Sep 21 '16 at 19:53
  • @mbish75 I don't think you can do this without recurssion or a loop. You have to repeat the same steps several times and those are our two options good repetition. – Code-Apprentice Sep 21 '16 at 21:07
  • @mbish75 You are right that mod 10 gives the ones digit. How do you get rest of the digits (from the tens place on)? – Code-Apprentice Sep 21 '16 at 21:09
  • @Code-Apprentice .That's what I assumed. My professor supplemental question was: 2. This time you have to think hard to improve your program. Write a separate program which does the same work but without doing all the steps. You have to do it without using any loop (for/while) or recursion. Your Output should look exactly like this : ######################### output ########################### Enter a number : 96374 This is easy!!! Your answer is 2. – mbish75 Sep 21 '16 at 22:42
  • @mbish75 Since your professor is asking you to do it, there must be a way. The trick is that you have to find an equivalent algorithm which gives the same output. For one thing that means you don't actually add anything. You will need to think outside the box. – Code-Apprentice Sep 21 '16 at 23:50
  • @mbish75 wait! How is the sum of those digits 2? I believe you left something out. – Code-Apprentice Sep 21 '16 at 23:52
  • @Code-Apprentice Its copy and pasted. Maybe it's similar to the first. So it does all the computations 9+6+3+7+4= 29..2+9..11..2. Only it shows the iput and the last digit. Im still stuck on the algorithm without recursion or if/then. But hey Code I appreciate all that you have helped me with you are a good guy. I'm getting tired pf struggling with this. – mbish75 Sep 22 '16 at 01:37
  • @mbish75 so if I understand correctly the original program starts with a number, sums the digits, and if the result is more than one digit, sums again, repeating until only one digit remains. Is that right? If so them you can definitely do this without any recursion or looping. In fact it takes one line of code. – Code-Apprentice Sep 22 '16 at 15:18
  • @Code-Apprentice . I think I can do it in one line of code too!!. It's due tonight. Tell me If I'm right. You just keep using mod 10 and the sum.. mod 10 and the sum..ext in a continuous line then output the last digit. – mbish75 Sep 22 '16 at 16:52
  • @mbish75 no. That would require a loop. You need to think of a completely different approach. – Code-Apprentice Sep 22 '16 at 20:54
  • @mbish75 Here's a hint: do you know how to test if a number is divisible by 9? – Code-Apprentice Sep 22 '16 at 20:55
  • @Code-Apprentice Shoot.. %9. the mod 9 Idk. I can hand in the work I have and still get partial credit – mbish75 Sep 22 '16 at 23:26
  • @mbish75 you are on the right track. Try some examples. – Code-Apprentice Sep 22 '16 at 23:36
  • If there was a way to 5 star you I would thanks for the guidance @Code-Apprentice – mbish75 Sep 23 '16 at 00:28
0

This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.

public static void main(String []args){

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt(); 
    printSingleDightSum(n);
 } 
 public static void printSingleDightSum(int N) {
     int sum = 0;
     int num = N;

     while(num !=0 ){
         int a = num%10;
         sum + = a;
         num = num/10;
     }
     if(sum < 10) {
         System.out.println('single digit sum is '+sum);
         return;

     } else {
         printSingleDightSum(sum);
     }
 }
Cyclotron3x3
  • 2,188
  • 23
  • 40
0

Here is the code, I will add comments and an explanation later but for now here is the code:

package numout;
import java.util.Scanner;

public class NumOut {

    public static void main(String[] args) {
        System.out.println("################### output example 1");
        System.out.print("Enter number: ");
        final int n = new Scanner(System.in).nextInt(); 
        System.out.print("\nI am Calculating.....");
        sumSums(n, 1);
    }

    public static int sumSums(int n, int step) {
        System.out.print("\n\nStep " + step + " : ");
        final int num = sumDigit(n);
        System.out.print("= " + num);
        if(num > 9) {
            sumSums(num, step+1);
        }
        return num;
    }

    public static int sumDigit(int n) {

        int modulo = n % 10;

        if(n == 0) return 0;

        final int num = sumDigit(n / 10);

        if(n / 10 != 0)
            System.out.print("+ " + modulo + " ");
        else
            System.out.print(modulo + " ");

        return modulo + num;

    }

}
  • Would there be a way to perform this program without recursion: loops, if/then, returns. @Brett Duncan – mbish75 Sep 21 '16 at 19:19