Recursive Method Prints 4 Times

后端 未结 4 646
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 04:05

So I am working on learning how to utilize recursion through Java. I have written a simple program that adds all the numbers between 1 and n and it looks to do it\'s job. Wh

4条回答
  •  天命终不由人
    2021-01-17 04:22

    It is because of the second print statement below the else. On execution the recursive function is called and it doesn't reach the print statement at the bottom. But after n=1 ie the if condition is executed then it return to the function recursive(2-1) and go to the down and return sum (also the print) and return the value of sum to the place where recursive(3-1) is called and so on.. . That is where it prints each sum.

    A Code which prints only the final sum is give below.Print is included in the main to print final answer only I hope this will help.

    public class add {
    
        public static void main(String[] args) {
    
            int sum = recursiveCall(5);
            System.out.println(sum); // this will print 15
        }
    
        public static int recursiveCall(int num) {
    
            int sum = 0;
    
            if(num == 1) {
    
                sum = 1;
                //System.out.println(sum); this will print 1
                return sum;
            }
            else {
    
                sum = recursiveCall(num - 1) + num;
            }
            // System.out.println(sum); //this is the reason for each sum.
            return sum;
    
        }
    
    }
    

提交回复
热议问题