C# program to create gray code

Here, we are going to learn how to create gray code in C#? By Nidhi Last updated : April 15, 2023

Creating Gray Code

Here we will gray code of numbers. The gray code is an encoding technique. The gray code is often known as "reflected" code.

C# code for creating Gray code

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.

for (loop = 0; loop < 5; loop++)
{
    Console.WriteLine(string.Format("{0}\t{1}", loop, Convert.ToString((int)CreateGraycode(loop), 2)));
}

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.