Modify array by removing ( arr [ i ] + arr [ i + 1 ] ) th element exactly K times | java program for the above approach ; Function to modify array by removing every K - th element from the array ; Check if current element is the k - th element ; Stores the elements after removing every kth element ; Append the current element if it is not k - th element ; Return the new array after removing every k - th element ; Function to print the array ; Traverse the array l [ ] ; Function to print the array after performing the given operations exactly k times ; Store first N natural numbers ; Iterate over the range [ 0 , k - 1 ] ; Store sums of the two consecutive terms ; Remove every p - th element from the array ; Increment x by 1 for the next iteration ; Print the resultant array ; Driver Code ; Given arrays ; Function Call
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int [ ] removeEveryKth ( int l [ ] , int k ) { for ( int i = 0 ; i < l . length ; i ++ ) { if ( i % k == 0 ) l [ i ] = 0 ; } ArrayList < Integer > list = new ArrayList < > ( ) ; list . add ( 0 ) ; for ( int i = 1 ; i < l . length ; i ++ ) { if ( l [ i ] != 0 ) list . add ( l [ i ] ) ; } return list . stream ( ) . mapToInt ( i -> i ) . toArray ( ) ; } static void printArray ( int l [ ] ) { for ( int i = 1 ; i < l . length ; i ++ ) System . out . print ( l [ i ] + " ▁ " ) ; System . out . println ( ) ; } static void printSequence ( int n , int k ) { int l [ ] = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) l [ i ] = i ; int x = 1 ; for ( int i = 0 ; i < k ; i ++ ) { int p = l [ x ] + l [ x + 1 ] ; l = removeEveryKth ( l , p ) ; x += 1 ; } printArray ( l ) ; } public static void main ( String [ ] args ) { int N = 8 ; int K = 2 ; printSequence ( N , K ) ; } }