Java Write a method that accepts an integer argument and re

Java : Write a method that accepts an integer  argument and returns the sum of all the integers
from 1 up to (and including) the number passed as an argument . For example, if 3 is passed
as an argument , the method will return the sum of 1+2+3, which is 6. Use recursion to calculate the sum .

Test your method in main by prompting the user to enter a positive integer to sum up to.
Provide input validation so that only positive values are accepted

Solution

SumIntegers.java


import java.util.Scanner;

class Sumintdemo {//class

    int sum = 0;

    public int getNumberSum(int number) {//recursive function
sum=0;
        if (number == 0) {
            return sum;
        } else {
            for (int i = 1; i <= number; i++) {
                sum = sum + i;//coputing sum
            }
        }
        return sum;
    }

}

public class SumIntegers {//main class or driver class

   //varaible assignment
    public static void main(String a[]) {//main method
        int num;
        int sum = 0;
        Sumintdemo mns = new Sumintdemo();
        do{
          
        System.out.print(\"Enter the number :\");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();//keyboard inputting
        if(num<0){
            System.out.println(\"please enter positive number only \");
            System.exit(0);
        }
        System.out.println(\"Sum is: \" + mns.getNumberSum(num));
        }while(num>0);
        }

}


output

Enter the number :5
Sum is: 15
Enter the number :6
Sum is: 21
Enter the number :-2
please enter positive number only

Java : Write a method that accepts an integer argument and returns the sum of all the integers from 1 up to (and including) the number passed as an argument . F
Java : Write a method that accepts an integer argument and returns the sum of all the integers from 1 up to (and including) the number passed as an argument . F

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site