The sum of the first n positive integers is s u m left paren
The sum of the first n positive integers is:
s u m left parenthesis n right parenthesis equals sum subscript i equals 1 end subscript superscript n i
and can easily be computed using a for-loop:
public int sumToN(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
{ sum += i; }
return sum; }
It is also possible to recursively compute the sum by recognizing that sum(n) = n + sum(n - 1).
Write a recursive version of sumToN(...).
Solution
SumOfNValues.java
import java.util.Scanner;
public class SumOfNValues {
public static void main(String[] args) {
//Declaring variables
int n,sum=0;
//Scanner class object is used to read the values entered by the user
Scanner sc = new Scanner(System.in);
//Getting the number entered by the user
System.out.print(\"Enter no of Positive Integers You want to add :\");
n=sc.nextInt();
//Calling te method by passing the number as argument
sum=SumOfNos(n);
//Displaying the sum of the numbers till the number entered by the user
System.out.println(\"Sum of first \"+n+\" numbers is :\"+sum);
}
//This method is used to return the sum of numbers recursively.
private static int SumOfNos(int n) {
if(n>0)
return n+SumOfNos(n-1);
else
return 0;
}
}
_____________________________________
Output:
Enter no of Positive Integers You want to add :8
Sum of first 8 numbers is :36
__________Thank You

