Find sum in range L to R in given sequence of integers | C ++ program to find the sum in given range L to R ; Function to find the sum within the given range ; generating array from given sequence ; calculate the desired sum ; return the sum ; Driven code ; initialise the range
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int L , int R ) { vector < int > arr ; int i = 0 ; int x = 2 ; while ( i <= R ) { arr . push_back ( i + x ) ; if ( i + 1 <= R ) arr . push_back ( i + 1 + x ) ; x *= -1 ; i += 2 ; } int sum = 0 ; for ( int i = L ; i <= R ; ++ i ) sum += arr [ i ] ; return sum ; } int main ( ) { int L = 0 , R = 5 ; cout << findSum ( L , R ) ; return 0 ; }