Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to calculate sum in recursive java function

Using recursion, create a program that will allow a user to enter five numbers. The program will provide the sum of all five numbers using recursive methods.

import java.util.Scanner;

public class Recursion {
    
    public static int Recursion1(int userSum) 
    {
        
        if (userSum == 0) {
            return userSum;
            } else {
            return userSum + Recursion1(userSum - 1);
            }

    }       
    
    public static void main(String[] args) 
    {
        int userSum = 0;
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Program Started");
        
        System.out.println(Recursion1(userSum));
    
        int counter = 0;
        int i;
        for(i=0;i < 5;i++) {
            //ask user input 
             System.out.print("Enter any number: ");
             userSum = scan.nextInt();
        }
          scan.close();
          int sumNum=Recursion1(userSum);
          System.out.println("The sum of digits is: "+sumNum);
          System.out.println("Scanner Closed.");
    }

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This should work as a recursive function. If you require any clarification let me know.

class MyClass {

    private final Scanner scan = new Scanner(System.in);

    public int sum(int count){
        System.out.print("Enter any number: ");
        int userSum = scan.nextInt();
        if(count == 4) {
            scan.close();
            return userSum;
        }
        count++;

        return userSum + sum(count);
    }

    public static void main(String[] args)
    {
       MyClass r = new MyClass();

       int sumNum =  r.sum(0);

        System.out.println("The sum of digits is: "+sumNum);
        System.out.println("Scanner Closed.");
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading