1
2
3
4
5
6
7
8
9
10
11 # include <iostream>
12 # include <math.h>
13 # define max (int)pow((double)2,(double)N)
14 using namespace std;
15
16
17 class GrayCounter
18 {
19 int N,*B,*G;
20 void printG();
21 void BinaryToGray();
22 void InitializeB();
23 void QueryN();
24 void Increment();
25 public:
26 void Algorithm();
27 }Gray;
28
29
30 void GrayCounter::printG()
31 {
32 int k;
33 cout << " ";
34 for (k=0;k<N;k++)
35 cout << G[k];
36 cout << "\n";
37 }
38
39 void GrayCounter::BinaryToGray()
40 {
41 G[0]=B[0];
42 for (int j=1;j<N;j++)
43 G[j]=B[j]^B[j-1];
44 printG();
45 }
46
47
48 void GrayCounter::InitializeB()
49 {
50 for (int i=0;i<N;i++)
51 B[i]=0;
52 }
53
54 void GrayCounter::QueryN()
55 {
56 cout << "\nPlease enter the number of bits for the Gray code counter: ";
57 cin >> N;
58 B= new int[N];
59 G= new int[N];
60 cout << "\n";
61 cout << "The output from the Gray code counter is:\n";
62 }
63
64 void GrayCounter::Increment()
65 {
66 int i,j,carry,temp;
67 for (i=max;i>1;i--)
68 {
69 for (j=N-1;j>-1;j--)
70 {
71 if (j==(N-1))
72 carry=1;
73 temp=B[j];
74 B[j]=temp ^ carry;
75 carry=temp & carry;
76 }
77 BinaryToGray();
78 }
79 }
80
81 void GrayCounter::Algorithm()
82 {
83 QueryN();
84 InitializeB();
85 BinaryToGray();
86 Increment();
87 }
88
89 int main()
90 {
91 Gray.Algorithm();
92 return 0;
93 }