Loading

Program to find the sum of the first N natural number by the iterative method:                    

package quipoin.javaeasyprograms;
public class SumOfNNatural {

	static int sum(int n) {
		int sum = 0;
		for (int i = 1; i <= n; i++) {
			sum += i;
		}
		return sum;
	}

	public static void main(String[] args) {
		System.out.println(sum(5));
	}
}

Output:

15

Program to find the sum of the first N natural number by the recursive method:

package quipoin.javaeasyprograms;
public class SumOfNNatural {

	static int sum(int n) {
		if (n == 0 || n == 1)
			return n;
		else
			return n + sum(n - 1);
	}

	public static void main(String[] args) {
		System.out.println(sum(5));
	}
}

Output:

15