CC-18 : Find sum of numbers from 1 to N.
Description:
Given an input num N find sum of numbers from 1 to N.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
| N: 5
|
Sum 1 to N: 15
|
| N: 9
|
Sum 1 to N: 45
|
Pseudocode:
sum1ToN(N):
| If N==1:
return 1.
|
| Else :
Return number calculated by adding N to return value from cum1ToN(N-1).
|
Code:
private int sum1ToN(int N){
if (N == 1) {
return 1;
}
int sum= N + sum1ToN(N-1);
return sum;
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionSum1ToN {
private int sum1ToN(int N){
if (N == 1) {
return 1;
}
int sum= N + sum1ToN(N-1);
return sum;
}
public static void main(String[] args) {
/************************
Test cases given below:
**********************/
int retVal;
try {
RecursionSum1ToN rcn=new RecursionSum1ToN();
int num=5;
System.out.println("N: "+num);
retVal=rcn.sum1ToN(num);
System.out.println("Sum 1 to N: "+retVal);
System.out.println();
num=9;
System.out.println("N: "+num);
retVal=rcn.sum1ToN(num);
System.out.println("Sum 1 to N: "+retVal);
System.out.println();
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}