Saturday, June 25, 2011

Given n Boolean variables x1,x2,...xn , we wish to print all possible combinations of truth values they can assume. For instance, if n=2, there are four possibilities: 'true,true','false,true','true,false' and 'false,false'. Write a C program to do this. Q#3,Page#17, 'Fundamentals of Data Structures in C (2nd Edition)' by 'Horowitz and Sahni'

#include<stdio.h>
#include<conio.h>

void comb(char *,int,int);
char toggle(char);

void main()
{
 char list[4]={'t','t','t','t'};
 int i=0,n=3;
 comb(list,i-1,n);
 getch();
}

void comb(char *list,int i,int n)
{
 int j,k;
 if(i==n)
 {
  for(j=0;j<=n;j++)
  printf("%c",list[j]);
  printf("  ");
 }
 else
 {
  for(k=0;k<=1;k++)
  {
   comb(list,i+1,n);
   list[i+1]=toggle(list[i+1]);
  }
}
}

char toggle(char c)
{
 if(c=='t')
 return 'f';
 else
 return 't';
}

1 comment:

  1. thanks for giving this example and also please you can post algorithm immediately

    ReplyDelete