text: Count of pairs having each element equal to index of the other from an Array | Java Program to implement the above approach ; Function to print the count of pair ; Iterate over all the elements of the array ; Increment the count ; Print the result ; Driver Code
code: import java . util . * ; class GFG { static void countPairs ( int N , int [ ] arr ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == arr [ arr [ i ] - 1 ] - 1 ) { count ++ ; } } System . out . println ( count / 2 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 4 , 3 } ; int N = arr . length ; countPairs ( N , arr ) ; } }