Binary Counter

#include<iostream>
#include<cmath> // for pow() function
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;
    }
}

int main()
{
    // Declare variables
    int k, i, steps;
    cout << "Enter the number of bits: ";
    cin >> k;
   
    // Input binary number
    cout << "Enter the binary number (from right to left): ";
    int arr[k];
    for (i = 0; i < k; i++)
    {
        cin >> arr[i];
    }

    // Input number of steps to increment
    cout << "Enter the number of steps to increment: ";
    cin >> steps;

    // Print initial binary number
    cout << "Initial binary number: ";
    for (i = k-1; i >= 0; i--)
    {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Increment the binary number for specified steps and print
    for (int j = 0; j < steps; j++)
    {
        // Increment the binary number
        increment(arr, k);

        // Print the current binary number
        cout << "Binary number after step " << j+1 << ": ";
        for (i = k-1; i >= 0; i--)
        {
            cout << arr[i] << " ";
        }
        cout << endl;
    }

    return 0;
}

Comments