Program to find sum of first n natural numbers | Efficient CPP program to find sum of first n natural numbers that avoids overflow if result is going to be within limits . ; Returns sum of first n natural numbers ; If n is odd , ( n + 1 ) must be even ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSum ( int n ) { if ( n % 2 == 0 ) return ( n / 2 ) * ( n + 1 ) ; else return ( ( n + 1 ) / 2 ) * n ; } int main ( ) { int n = 5 ; cout << findSum ( n ) ; return 0 ; }