dimanche 24 juillet 2016

Generate all strings of "n" bits?

Me and a friend of mine were working on this code today that generated all possible strings of "n" bits where n is taken as an input from the user. Here's the code for reference

#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<process.h>

using namespace std;

char A[400];

void allStringsOfNBits(int num)
{
    if (num < 1)
        printf("%sn", A);
    else
    {
        A[num - 1] = '0';
        allStringsOfNBits(num - 1);
        A[num - 1] = '1';
        allStringsOfNBits(num - 1);
    }
}

int main()
{
    cout << "Enter value of n to generate all strings of n bits: ";
    int n;
    cin >> n;
    if (n < 1)
    {
        cout << "Illegal value entered, the program will now exit.";
        exit(0);
    }
    else
        allStringsOfNBits(n);
    _getch();
    return 0;
}

Though the code runs and works just fine, could someone please explain me how the recursive function allStringsOfNBits(int num) works?

Aucun commentaire:

Enregistrer un commentaire