binarycounter
#include<iostream>
using namespace std;
// Function to increment a k-bit binary number represented as an array
void increment(int A[], int k)
{
int i = 0;
while (i < k && A[i] == 1)
{
A[i] = 0;
i++;
}
if (i < k)
{
A[i] = 1;
}
return;
}
int main()
{
// Declare an array to store the binary number and initialize it to 0
int arr[10], k, i;
cout << "Enter the number of bits: ";
cin >> k;
for (i = 0; i < k; i++)
{
arr[i] = 0;
}
// Continuously increment the binary number until it reaches 0 again
int prev = 0;
do {
// Print the current binary number
for (i = k-1; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << "\n";
// Increment the binary number
increment(arr, k);
// Convert the binary number to an integer for comparison
int cur = 0;
for (i = k-1; i >= 0; i--) {
cur = cur * 2 + arr[i];
}
prev = cur;
} while (prev != 0);
return 0;
}
Comments
Post a Comment