MCPcopy Create free account
hub / github.com/chaharnishant11/CodeIn10DSA / nSum

Class nSum

Recursion/Code/sumFirstN.java:2–28  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.*;
2class nSum
3 {
4
5 static int sum(int n)
6 {
7 if(n==1) // base condition;
8 return 1;
9
10 int recResult = sum(n-1);
11 int smallCal = n+recResult;
12
13 return smallCal;
14
15
16 //return (n == 1 ) ? 1 : n + sum(n - 1); //--One liner using ternary operator.
17 }
18
19 // Driver Code
20 public static void main(String args[])
21 {
22 Scanner in = new Scanner(System.in);
23 System.out.print("Enter a number : ");
24 int n = in.nextInt();
25
26 System.out.println("Sum of " + n + " is " + sum(n));
27 }
28}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected