Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   C Program to Calculate all possible Combinations of an n Digit Number (http://www.go4expert.com/articles/c-program-calculate-combinations-n-digit-t25380/)

teacher 30Mar2011 21:34

C Program to Calculate all possible Combinations of an n Digit Number
 
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);
}


Suda51 17Apr2011 19:33

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

teacher 17Apr2011 20:28

Re: C Program to Calculate all possible Combinations of an n Digit Number
 
You can say thanks by clicking on the thanks button...


All times are GMT +5.5. The time now is 03:07.