×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

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

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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