Write a program to find the sum of N natural numbers.
Example 1:
Input: n=100
Output: 5050
Approach 1: Using loop through 1 to n.
Java
public class NaturalNumberSum {public static void main(String[] args) {int num = 100;int sum = sumNatural(num);System.out.println("Sum is " + sum);}private static int sumNatural(int num) {int sum = 0;for (int i = 1; i <= num; i++) {sum += i;}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the//sum of n natural numberint sumOfNauralnumber(int n){int sum=0;for(int i=1;i<=n;i++)sum+=i;return sum;}int main(){int n=100;int sum=sumOfNauralnumber(n);cout<<"Sum of n natural number is ";cout<<sum<<"\n";return 0;}
Approach 2: Using the formula. Sum=n*(n+1)/2
Java
public class NaturalNumberSum1 {public static void main(String[] args) {int num = 100;int sum = sumNatural(num);System.out.println("Sum is " + sum);}private static int sumNatural(int num) {// formula sum=n*(n+1)/2int sum = num * (num + 1) / 2;return sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the//sum of n natural numberint sumOfNauralnumber(int n){int sum=n*(n+1)/2;return sum;}int main(){int n=100;int sum=sumOfNauralnumber(n);cout<<"Sum of n natural number is ";cout<<sum<<"\n";return 0;}
No comments:
Post a Comment