Find sum in range L to R in given sequence of integers | Java 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 ; Driver code ; Initialise the range
import java . util . * ; class GFG { public static int findSum ( int L , int R ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; int i = 0 ; int x = 2 ; while ( i <= R ) { arr . add ( i + x ) ; if ( i + 1 <= R ) arr . add ( i + 1 + x ) ; x *= - 1 ; i += 2 ; } int sum = 0 ; for ( i = L ; i <= R ; ++ i ) sum += arr . get ( i ) ; return sum ; } public static void main ( String [ ] args ) { int L = 0 , R = 5 ; System . out . println ( findSum ( L , R ) ) ; } }