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

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

1. ### teacherNew Member

Joined:
Mar 27, 2011
Messages:
66
8
Trophy Points:
0
Occupation:
i hate jobs
Location:
india,agra
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. 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. ### Suda51New Member

Joined:
Apr 17, 2011
Messages:
1
0
Trophy Points:
0
thanks

Joined:
Mar 27, 2011
Messages:
66