2

I need to print all binary string of length N counting from 0 to the highest number that can represented. My code below works for generating all of the strings. The problem I am having is that the strings are not in order from least to greatest.

#define MAX_LENGTH 10

char binarystrings[MAX_LENGTH];

void binary(int n) {
    if (n == 0) {
        printf("%s\n", binarystrings);
    } else {
        binarystrings[n-1] = '0';
        binary(n-1);
        binarystrings[n-1] = '1';
        binary(n-1);
    }
}

int main() {
    int length;
    scanf("%d", &length);
    binary(length);
}

When my program takes in 3 it generates:

000
100
010
110
001
101
011
111

But I need it to generate:

000
001
010
011
100
101
110
111

How should I go about making my program put the numbers out in the right order?

2
  • 1
    Did you notice that the reverse of each line is in the order you want? Commented Feb 23, 2019 at 18:43
  • Yes, I did. I could've used used string reverse but it wouldn't have helped me to see why they were out of order. I now see that I was filling the array backwards so now I can avoid string reverse entirely. Commented Feb 23, 2019 at 19:20

3 Answers 3

1

You are filling the binarystring right to left. Fill it left to right instead. For that you need to pass two parameters (e.g. position and length) to binary:

void binary(int index, int length)
{
    if (index == length)
        return;
    binarystring[index] = 0;
    binary(index + 1, length);
    binarystring[index] = 1;
    binary(index + 1, length);
}

and call it as binary(0, length).

Sign up to request clarification or add additional context in comments.

Comments

0

what about printf("%s\n", strrev(binarystrings)); It would probably be safer to reverse the string and check for error then print it and initializing your char array to contain nulls..and finally doesn't the array need to be MAX_LENGTH +1

Comments

0

u can try my code ... i have got the answer in the right pattern:

enter code here

#include <stdio.h>
void printBinary(int a[],int n){
    
    for (int i=0;i<n;i++){
        printf("%d",a[i]);
    }
    printf("\n");
    
}

void generateBinaryString(int n,int a[],int i){
    
    if (i==n){
        printBinary(a,n);
        return;
    }
    
    a[i]=0;
    generateBinaryString(n,a,i+1);
    a[i]=1;
    generateBinaryString(n,a,i+1);
}

int main()
{
    int n;
    printf("printing the binary string for n nos.");
    scanf("%d",&n);
    int a[n];
    
    generateBinaryString(n,a,0);

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.