1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

C Program to Calculate all possible Combinations of an n Digit Number

Discussion in 'C' started by teacher, Mar 30, 2011.

  1. teacher

    teacher New Member

    Generally a question is asked that if you have given n bits then print out all the possible binary numbers of n bit and so I will try to explain how to get that done. Please don't Copy Paste. Understand The logic because it is useful in other problems as well

    for eg
    if n=1 then you can have
    0
    1
    if n=2 then you can have
    00
    10
    01
    11

    Similarly if n=3 then you can have 8 possible combination.

    In general for a n bit number you can have 2 to the power n possible numbers. :D

    Code:
    #include <stdio.h>
    #define ARRAY_SIZE 200
    /* FUNCTIONS DECLARATIONS */
    void find_all_possible_binary(int ,int );
    void push(int );
    void pop();
    
    /******************************************************************************
    * SIMPLE LIFO STACK .YOU CAN ADJUST ARRAY_SIZE ACCORDING TO YOUR SYSTEM MEMORY
    replace pf with printf
    */
    int stack[ARRAY_SIZE];
    int top;
    
    void push(int x){
    	stack[++top]=x;
    }
    
    void pop(){
    	stack[top--];
    }
    /******************************************************************************/
    
    void find_all_possible_binary(int x,int temp)
    {
    	int i;
    	if(temp!=-1){
    		push(temp);
    	} 
    	if(x==0){
    		for( i=0;i<=top;++i)
    			pf("%d",stack[i]);
    		pf("\n");
    		pop();
    	}
    	else{   
    		find_all_possible_binary(x-1,0);
    		find_all_possible_binary(x-1,1);
    		pop();        
    	}
    }
    int main(){
    	int no_of_bits;
    	top=-1;
    	pf("Enter number of bits: ");
    	scanf("%d",&no_of_bits);
    	find_all_possible_binary(no_of_bits,-1);
    }
    
     
    shabbir and (deleted member) like this.
  2. Suda51

    Suda51 New Member

    thanks
     
  3. teacher

    teacher New Member

    You can say thanks by clicking on the thanks button...
     

Share This Page