Sum of first N natural numbers with alternate signs | Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If is an even number ; Update alternateSum ; If i is an odd number ; Update alternateSum ; Driver Code
function alternatingSumOfFirst_N ( N ) { var alternateSum = 0 ; for ( i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) { alternateSum += - i ; } else { alternateSum += i ; } } return alternateSum ; } var N = 6 ; document . write ( alternatingSumOfFirst_N ( N ) ) ;