-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.

4
  • Check out this explanation of the Fibonacci recursive program written in Java: Java recursive Fibonacci sequence. This should give you insight on what you need to do. Sep 21, 2016 at 1: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, 2016 at 1: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. Sep 21, 2016 at 1: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, 2016 at 1:43

3 Answers 3

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.

15
  • 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, 2016 at 1: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, 2016 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. Sep 21, 2016 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)? Sep 21, 2016 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, 2016 at 22:42
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);
     }
 }
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;

    }

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.