The source code to create a gray code is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to create gray code.
using System;
class Program
{
public static int CreateGraycode(int num)
{
int gray = 0;
gray = num ^ (num >> 1);
return gray;
}
static void Main(string[] args)
{
int loop = 0;
Console.WriteLine("Number\tGray Code");
for (loop = 0; loop < 5; loop++)
{
Console.WriteLine(string.Format("{0}\t{1}", loop, Convert.ToString((int)CreateGraycode(loop), 2)));
}
}
}
Output:
Number Gray Code
0 0
1 1
2 11
3 10
4 110
Press any key to continue . . .
Explanation:
In the above program, we created a class Program that contains two static methods CreateGrayCode() and Main(). The CreateGrayCode() method is used to convert a number into a gray code.
In the Main() method, we convert numbers into gray code using for loop and print them on the console screen.
Program:
The source code to create a gray code is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Program that contains two static methods CreateGrayCode() and Main(). The CreateGrayCode() method is used to convert a number into a gray code.
In the Main() method, we convert numbers into gray code using for loop and print them on the console screen.