Generate n | C # program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function
using System ; using System . Collections . Generic ; public class GfG { public static void generateGrayarr ( int n ) { if ( n <= 0 ) { return ; } List < string > arr = new List < string > ( ) ; arr . Add ( "0" ) ; arr . Add ( "1" ) ; int i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) { arr . Add ( arr [ j ] ) ; } for ( j = 0 ; j < i ; j ++ ) { arr [ j ] = "0" + arr [ j ] ; } for ( j = i ; j < 2 * i ; j ++ ) { arr [ j ] = "1" + arr [ j ] ; } } for ( i = 0 ; i < arr . Count ; i ++ ) { Console . WriteLine ( arr [ i ] ) ; } } public static void Main ( string [ ] args ) { generateGrayarr ( 3 ) ; } }