C# program to create gray code

Here, we are going to learn how to create gray code in C#?
Submitted by Nidhi, on September 14, 2020

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

Program:

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)));
}





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.