0

This is the code from geeksforgeeks which generates and print bitstrings of n bits but I want to know instead of printing the array, how can I store the values of the array or return it so I can use the values in the main method.

import java.util.*; 

class GFG 
{ 

// Function to print the output 
static void printTheArray(int arr[], int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 
        System.out.print(arr[i]+" "); 
    } 
    System.out.println(); 
} 

// Function to generate all binary strings 
static void generateAllBinaryStrings(int n, 
                            int arr[], int i) 
{ 
    if (i == n) 
    { 
        printTheArray(arr, n); 
        return; 
    } 

    // First assign "0" at ith position 
    // and try for all other permutations 
    // for remaining positions 
    arr[i] = 0; 
    generateAllBinaryStrings(n, arr, i + 1); 

    // And then assign "1" at ith position 
    // and try for all other permutations 
    // for remaining positions 
    arr[i] = 1; 
    generateAllBinaryStrings(n, arr, i + 1); 
} 

// Driver Code 
public static void main(String args[]) 
{ 
    int n = 4; 

    int[] arr = new int[n]; 

    // Print all binary strings 
    generateAllBinaryStrings(n, arr, 0); 
} 
} 

// This code is contributed by 
// Surendra_Gangwar 

1 Answer 1

-1
  1. Change the return type
  2. Add a return statement

Like this:

// Function to generate all binary strings 
static int[] generateAllBinaryStrings(int n, 
//     ^^^^^ change return type
                            int arr[], int i) 
{ 
    if (i == n) 
    { 
        printTheArray(arr, n); 
        return; 
    } 

    // First assign "0" at ith position 
    // and try for all other permutations 
    // for remaining positions 
    arr[i] = 0; 
    generateAllBinaryStrings(n, arr, i + 1); 

    // And then assign "1" at ith position 
    // and try for all other permutations 
    // for remaining positions 
    arr[i] = 1; 
    generateAllBinaryStrings(n, arr, i + 1); 

    return arr;
//  ^^^^^^^^^^^ add return statement
} 
Sign up to request clarification or add additional context in comments.

2 Comments

I did that but it only returns 1
Well I think you should make an attempt at making changes to the code. We're not a code writing service after all.

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.