Sunday, October 13, 2013

Digital Clock

Wow, really been a long time.

I always have had an eye for clocks. Mostly on clocks, too. i keep on thinking how they work, how does the digital watch works. And then Fundamentals Of Digital Electronics happened to me. When I studied about gates and flip-flops, I started look at the digital world with a new eye. I started to think, about what could be beneath the surface, what would be the local behind its working. And this curiosity lead me to making of my first logisim project, The Digital Clock. And, it has been ticking for some time.

Uploading the link, as my project The Digital Clock is open to reviews and modification
Am loving it. Feels great and really amazing.
Have a happy holiday
Manmohit


Saturday, January 19, 2013

THE SUDOKU (NxN) SOLVER IN C

//The only requirement is that N is a perfect square, 4, 9, 16.....
//IN CASE OF DOUBT, KINDLY COMMENT IT

# include<stdio.h>
# include<math.h>
# define N 4
# define SQ ((int)(sqrt(N)))
int check(int a[][N], int b, int c, int val)
{
int i, j;
for(i = 0; i < N; i++)
{
if(a[b][i] == val || a[i][c] == val)
{
return 0;
}
}
for(i = b-(b % SQ); i < b + (SQ - (b % SQ)); i++)
{
for(j = c-(c % SQ); j < c + (SQ - (c % SQ)); j++)
{
if(a[i][j] == val)
{
return 0;
}
}
}
return 1;
}
void input(int a[][N])
{
int i = 1;
int b,c, d;
while(i > 0)
{
scanf("%d, %d, %d", &b, &c, &d);
a[b][c] = d;
scanf("%d", &i);
}
}
void main()
{
int a[N][N], val = 1, i , j, b[N][N], k, l, m;
for(i = 0; i < N; i++)
{
for(j = 0; j < N ; j++)
{
a[i][j] = 0;
b[i][j] = 0;
}
}
printf("THIS IS A %d BY %d MATRIX\n", N,N);
printf("INPUT IN THE FORMAT: X(0-%d), Y(0-%d), VAL(1-%d)\n", N-1, N-1, N);
printf("ENTER 0 TO STOP INPUTTING AND 1 TO CONTINUE\n");
input(a);
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
val = 1;
if (a[i][j] == 0)
{
reloop:
if(check(a,i,j,val) == 1)
{
a[i][j] = val;
b[i][j] = 1;
continue;
}
else
{
restart:
if(val < N)
{
val++;
goto reloop;
}
else
{
a[i][j] = 0;
b[i][j] = 0;
l = 0;
retry:
for(k = 0; k < N; k++)
{

if(b[i][k] == 1)
{
l++;
m = k;
}
}
if(l == 0)
{
i--;
goto retry;
}
val = a[i][m];
a[i][m] = 0;
b[i][m] = 0;
j = m;
goto restart;
}
}
}
}
}
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}

Wednesday, December 5, 2012

Program covering basics of linked list

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<iostream.h>
struct node
 {   int num;
      struct node *link;
 };
node *start , *save , *newptr , *ptr;
node * create_node ( int n )
{
      ptr  = ( node * )malloc(sizeof(struct node));
      ptr -> num = n;
      ptr -> link = NULL;
      return ptr;
}
void insert_node ( node *np , int n )
{
     node *tmp;
     if( start == NULL )
          start = np;
     else
     {    tmp = start;
          while (  tmp != NULL)
          { if ( tmp -> num <= n && ( tmp -> link -> num > n || tmp -> link == NULL))
                { np -> link = tmp -> link;
                   tmp -> link = np;
                   return;
                 }
            tmp = tmp -> link;
           }
      }
}
void del_beg()
{
         if ( start == NULL)
             printf("\nUnderflow");
        else
       {
             ptr = start;
             start = start -> link;
             free(ptr);
       }
}
void del (int inf)
{           ptr = start;
             node *tmp;
             while( ptr != NULL )
            {
                     if( ptr-> num == inf)
                    {        if ( ptr == start )
                              {    start = ptr ->link;
                                    free(ptr);
                                     return;
                              }
                             else
                             {      tmp = ptr;
                                     ptr = ptr->link;
                                     free(tmp);
                                     return;
                             }
                     }
                  else
                        ptr = ptr -> link;
              }
}
  void display ( node *np )
{
                 while (np != NULL )
                {     printf("%d" , np -> num );
                       printf("->>");
                       np = np -> link;
                 }
}
void main()
{
       clrscr();
       start = NULL ;
       int inf , ch1;
       char ch ;
       do
       {     printf("\n1.Insertion");
              printf("\n2.Deletion from begining");
              printf("\n3.Display");
              printf("\n4.Deletion of your choice");
              printf("\nEnter your choice:\t");
              scanf("%d" , &ch1 );
              switch(ch1)
             {    case 1:
                   printf("\nEnter the information of the new node:\t");
                   scanf("%d" , &inf );
                   printf("\nCreating new node!!! press Enter to continue");
                   getch();
                   newptr = create_node( inf ) ;
                   insert_node( newptr , inf );
                   display(start);
                   break;
                   case 2:
                   del_beg();
                    break;
                    case 3:
                    display(start);
                     break;
                    case 4:
                     printf("\nEnter the node to be delted:\t");
                     scanf( "%d" , inf );
                     del(inf);
                     break;
             }
              printf("\nDo you want to continue:\t");
              cin>>ch;
       }while ( ch == 'y' || ch == 'Y' );
       getch();
}

Structure solution


0Ans 10.3   Given is the structure declaration
                struct abc
                {              int x;
                                float y;
                                char z;
                }
                Following are the statements which declare and initialize the structure variable :
struct  a , b , c ; // Error The structure variable will not be declared as tag name abc  is         missing             
<!--[if !supportLists]-->II.                  <!--[endif]-->struct abc a , b , c ; //Correct Declaration
<!--[if !supportLists]-->III.                <!--[endif]-->abc  x , y , z ;   //Error the structure variable will not be declared as struct keyword is missing
<!--[if !supportLists]-->IV.                <!--[endif]-->struct abc a[] ;  //Error Array size is  missing
<!--[if !supportLists]-->V.                  <!--[endif]-->struct abc a = { }; // a is assigned a value which is never used
<!--[if !supportLists]-->VI.                <!--[endif]-->struct abc = b , { 1+2 , 3.0 , “xyz”}  //Error syntactically wrong
<!--[if !supportLists]-->VII.              <!--[endif]-->struct abc c = { 4 , 5 , 6 } //Error last member is a character it should be enclosed in single quotes
<!--[if !supportLists]-->VIII.            <!--[endif]-->struct abc a = 4 , 5.0 , “xyz” ; //Error Initialization values should be enclosed in curly braces
Ans 10.4   None of the given statements in the question  is  legal
Ans 10.5  For The given declaration
                struct item_bank
                {              int number;
                                Double cost;
                }
                Following are the correct statements
                (d)          struct item_bank items[10];
Ans 10.6   For the given declaration
                typedef struct abc
                {              char x;
                                int y ;
                                float z[10] ;
                }    ABC ;

Following declarations are invalid
<!--[if !supportLists]-->(a)    <!--[endif]-->struct ABC v3;
Ans 10.8 Purpose of the following is:
<!--[if !supportLists]-->a.       <!--[endif]-->Template
<!--[if !supportLists]-->b.      <!--[endif]-->struct keyword : is used declare , define and initialize a structure variable
<!--[if !supportLists]-->c.       <!--[endif]-->typedef keyword  : is used to declare the alias name for the existing datatype
<!--[if !supportLists]-->d.      <!--[endif]-->sizeof operator :  is used to get the size of the variable which is passed as parameter to the function
<!--[if !supportLists]-->e.      <!--[endif]-->tag name : it’s the name given to a structure defined by us using struct keyword
Ans 10.9  struct                                              // Tag name for structure is missing
                {              int number ;
                                float price ;
                }                                                              //; is missing
Ans 10.10 Use of the following is as given below:
<!--[if !supportLists]-->a.       <!--[endif]-->union -  The concept of union has been partially borrowed from the concept of structure the major difference being the members of union share same memory location whereas the members of structure share different memory location. We use union when we want a group of variables which we are using at different time but want them under a common data type we use union
<!--[if !supportLists]-->b.      <!--[endif]-->Bit fields – There are several instances when data requires much less than 16 bits space. For this we use bit fields which is a set of adjacent bits whose size can be from 1 to 16 bits in length
<!--[if !supportLists]-->c.       <!--[endif]-->The size of operator – this operator is used for determining the size occupied by  the variable in the memory which is provided as operand to the size of operator.
Ans 10.12  For th following declarations and definition
                struct abc
                {              int a;
                                float b ;
                };
                struct xyz
                {              int x;
                                float y; 
                };
                abc         a1  , a2;
                xyz         x1 , x2;
a1 = x1;    //Error two structure variables cannot be copied
<!--[if !supportLists]-->b.      <!--[endif]-->abc.a1 = 10.75; //Error structure variable cannot be initialized in this way
<!--[if !supportLists]-->c.       <!--[endif]-->int m  = a + x ; //Error structure members cannot be accessed in this way
<!--[if !supportLists]-->d.      <!--[endif]-->int n = x1.x + 10 // Correct
<!--[if !supportLists]-->e.      <!--[endif]-->a1 = a2 //Error two structure variables can be  copied only member wise not directly
<!--[if !supportLists]-->f.        <!--[endif]-->if (a.a1 > x.x1)   // Error the member should come after the variable name.
<!--[if !supportLists]-->g.       <!--[endif]-->if( a1.a < x1.x)   //Correct
<!--[if !supportLists]-->h.      <!--[endif]-->if (x1 != x2 )    //Error two structure variables cannot be compared directly




Ans 10.15   Computer stores structures using the concept of “ word boundary”. A  word is the natural/native amount of data fetched frommemory on a single access by a CPU. Now storing the data at the boundary of the word the data can be fetched very fast. The size of the word boundary is machine dependent. Now suppose  that the word boundary of the given machine is 4 byte. Now a structure having three data members char ,  int  ,  float will be stored in the memory as shown below . Now we can easily understand that the empty space will be there  this empty byte in between the two data members is termed as slack byte.






Ans 10.16 The various points to be considered while implementing bit field are as follows:
          i. We cannot take address of a bit field variable. Therefore we cannot use scanf function for reading     them and neither we can use pointer variable for such type of structure.
ii.     Bit fields cannot be arrayed.
iii.    Bit fields should be assigned values that are within the range of the of their size.
Ans 10.19 
typedef struct product
                {              char name[10];
                                float price ;
                }              PRODUCT products[10] ;                               // Error Immediately after the alias name variable
                                                                                                                cannot be declared
//Correct mode
typedef struct product
                {              char name[10] ;
                                float price;
                }              PRODUCT;
PRODUCT products[10];



Ans 10.20
Output:
8                                                                              Explanation union will occupy the space according to largest member of the same
10                                                                           At a time only one member can use the memory location of the union
1.23                                                                        Same reason as above

Solution to Programing Exercise pointers

                                                    Solution to Programming Exercise Pointers
Guys i think the starting two programs  are quite easy and thus I am not providing the solutions to them
Ans 11.3

#include<stdio.h>
#include<conio.h>
int size;
void main()
{
clrscr();
void insert( int *ptr , int val);
int arr[10] , in , i ;
printf("\nEnter the size of the array:\t");
scanf("%d" , &size);
printf("\nEnter your sorted array:\t");
for( i = 0 ; i <  size ;  i++)
scanf("%d", &arr[i]);
printf("\nEnter the number you want to insert in the array:\t");
scanf("%d", &in);
insert(arr, in);
printf("\nThe array after insertion is:\t");
for ( i = 0 ; i < size ; i++ )
printf("%d " , arr[i] ) ;
getch();
}

void insert( int  *ptr , int val)
{ int pos , i ;
if ( val < *(ptr+0) )
pos = 0 ;
else
{ for( i = 0 ; i < size - 1 ; i++ )
{ if ( *(ptr+i) <= val && val < *(ptr+i+1) )
{ pos = i+1;
break;
}
}
if ( i == size-1 )
pos = size;
}
if ( size == 10)
printf("\nOverflow!");
for ( i = size ; i > pos ; i-- )
*(ptr + i) = *(ptr + (i - 1) ) ;
*(ptr + pos ) = val;
size++;
}

Ans 11.4

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int * add ( int *a[] , int *b[] );
int i , j , p[3][3] , q[3][3] , r[3][3];
printf("\nEnter a 3*3 Matrix:\n");
for( i = 0 ; i < 3 ; i++ )
for( j = 0 ; j < 3 ; j++ )
scanf("%d", p[i][j] ) ;
printf("\nEnter the second 3*3 Matrix;\n");
for( i =0 ; i < 3 ; i++)
for( j = 0 ; j < 3 ; j++ )
scanf( " %d " , q[i][j]  );
r = add( p , q );
printf("\nThe sum is:\t");
for ( i =0 ; i< 3 ; i++ )
for( j = 0 ; j < 3 ; j++ )
scanf( "%d" , r[i][j] );
getch();
}

int * add ( int *a[3] ,int *b[3] )
{
int  i , j , c[3][3] ;
for( i = 0 ; i < 3 ; i++ )
for( j = 0 ; j < 3 ; j++ )
c[i][j] = *( *(a + i ) + j )  + *( *(b + i ) + j );
       return c;
}

Ans 11.5

#include<stdio.h>
#include<conio.h>
void del ( char *ptr , char itm)
{
int i , pos , size;
for ( i = 0 , size = 0 ; * (ptr + i) != '\0' ; i++ , size++)
{
if( *(ptr + i ) == itm)
pos = i ;
}
for( i = pos ; i < size ; i++ )
*(ptr +i) = *(ptr+i+1);
*(ptr+size) = '\0';

}
void main()
{
clrscr();
char str[10] ,ch;
printf("\nEnter your string:\t");
gets(str);
printf("\nEnter the charcter:\t");
scanf("%c" , &ch);
del(str, ch ) ;
printf("\nYour string after deletion:\t%s", str);
getch();
}

Ans 11.6
#include<stdio.h>
#include<conio.h>
#include<iostream.h>

void main()
{
char * day_name( int no);
clrscr();
int n;
char * day;
printf("\nEnter the number of the day:\t");
scanf("%d" , &n ) ;
day = day_name( n );
printf("\nThe day is:\t%s" , day);
getch();
}
char * day_name ( int no )
{
static char * week_day[7] = { "Monday" , "Tuesday" , "Wednesday", "Thursday" , "Friday" , "Saturday", "Sunday"};
int i , pos = 0;
for ( i = 0 ; i < 7 ; i++ )
{
if( ( i+1 ) == no )
{ pos = i;
break ;
}
}
return week_day[pos];
}

Ans 11.7
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char *name[5] ;
int i ;
void sort ( char  *str[] );
printf("\nEnter any five names:\t");
for ( i = 0 ; i < 5 ; i++ )
gets(name[i]);
sort ( name ) ;
printf("\nThe names in the alphabetical order are:\n");
for ( i = 4 ; i >= 0 ; i-- )
puts(name[i]);
getch();
}

void sort ( char *str[5] )
{
int i , j ;
char *tmp ;
for ( i = 0 ; i < 5 ; i++ )
{ for ( j = 0 ; j < (5-1) - i ; j++ )
{ if ( strcmp( str[i+1] , str[i] )  > 0 )
{ tmp = str[i];
str[i] = str[i+1];
str[i+1] = tmp;
}
}
}
}

Ans 11.9#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
int a[5];
void reverse( int *p ) ;
printf("\nEnter the array:\t");
for (  i = 0 ; i <  5 ; i ++ )
sacnf("%d" , a[i] ) ;
reverse(a);
printf("\nThe reversed array is:\t");
for ( i = 0 i < 5 ; i++)
printf("%d" , a[i] );
getch();

}

void reverse ( int * p )
{
int i , tmp ;
for ( i = 0 , j = 4  ; i < 5/2 ; i++ ,  j-- )
{ tmp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = tmp;
}
}

Ans 11.10
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
int a[5] , b[5] , i , res;
int cmp(int *p , int *q );
printf("\nEnter the array:\t");
for ( i = 0 ; i < 5 ; i++ )
scanf("%d" , &a[i] ) ;
printf("\nEnter the second array:\t");
for ( i = 0 ; i < 5 ; i++ )
scanf( "%d" , &b[i]);
if ( cmp( a , b) == 1)
printf("\nThey are identical");
else
printf("\nThey are not identical");
getch();
}

int cmp ( int *p , int *q)
{
int  i , flag = 1;
for ( i = 0 ; i < 5 ; i++ )
{ if( *(p+i) != *(q+i) )
{ flag = 0;
}
}
return flag;
}



Friday, October 26, 2012

Solution to E Balaguruswamy Chapter - Pointers

                                                               Solution to E Balaguruswamy
                                                                     Chapter  - Pointers

Ans 11.4 Pointer is initialized by keyword NULL or  0  in the following fashion
int  * p = NULL  , * m = 0 ;
 Ans 11.5  Following is the effect of the following statements
i.                     int a, *b = &a;  //Error Pointer being initialized with the address of an uninitialized variable
ii.                   int p ,   *p ;      //Error Multiple Declaration of p
iii.                  char *s;          
iv.                 a = (float * ) &x);
v.                   double  ( *f )( ) ;       //It declares the pointer to a function

Ans 11. 6   int M ,  n ;
    int *P1  , *P2 ;
The following are the errors in the expression given below:
i)                    P1 = &m ; //Error Pointer cannot be initialized with an uninitialized variable
ii)                   P2 = n ; // Error Pointer can only be initialized with the address of the variable
iii)                 P2 = &*&m; // Correct as the first dereferencing operator Is over powered by the second & operator
iv)                  M = P2 – P1 //Correct Pointer Subtraction Is allowed
v)                  P1 = &P2 //Error A simple pointer cannot be initialized with memory address of an another pointer, only a pointer to a pointer can be initialized in this way
  Ans11.7 Difference between the notations  *m[5] and (*m)[3]. Since * has lower precedence than  [] , *m[5] declares m  as an array of 5 pointers while (*m)[3] declares m as a pointer to an array of five elements.
Ans 11.9   int x = 10 ,  y  = 10 ;
                    int  *p1 = &x , *p2 = &y;
                The following Expression generate the following output:
i)                    (*p1)++   Output – 10
ii)                   - - (*p2)   Output  -  9
iii)                 *p1 + (*p2)--   Output  - 20
iv)                   ++(*p2) - *p1  Output  -  1
Ans 11.12  Following Output is  generated by the following code :
                int m = 100 ;
                int *p1 = &m;
                int **p2 = &p1;
                printf(“%d” , **p2);
                Output :
                100
Ans 11. 13   Following is the error in the given code
                                int **p1 , * p2 ;
                                p2 = &p1  // It should be  p1 =&p2
Explanation: p1 is a pointer to a pointer so it should always point a pointer
Ans11.14  Difference between the two expression name + 10; and *(name + 10 ) is that the first expression refers to all the characters after the 10th position in the array name or rather simply we  can say that it will the array name from the 10th character whereas the second expression refers specifically to the 10th character of the array of name .
Ans 11.15  Following is the output of the code given below
                                int m[2] ;
                                *(m+1)
                                *m = *(m + 1);
                                printf(“ %d “ , m[0] );
Output:
                                100
Ans 11.16    int m[2];
                       int *p = m ;
                       m[0] = 100;
                       m[1] = 200;
                       printf(“%d %d “ , ++*p , *p );
                      Output:
                      101  100
Ans 11.17    Output of the following code :
                 int f(char *p );
                main()
                {              char str[] = “ANSI”;
                                printf(“%d” , f(str) );
                }
                int f(char *p )
                {              char *q = p ;
                                while (*++p ) ;
                                return (p – q );                  }
Output :
4
Ans 11.18  Following declarations are not the same:
                1 . void search ( int *m[] , int x) { }
                In this the parameter in the definition is a integer pointer array.
                2. void search ( int **m  ,int x ) {}
                In this the parameter in the definition is a integer pointer to a pointer.
Ans 11.19   Following declaration is are same
                char *s;
                char s[5] ;
                As name of the array is a pointer to the first element of the array it’s as same as declaring a pointers which when incremented can be used to store a list of values same as an array.
Ans 11.20  The following is the correct way to declare a pointer to a function.
                int (*p)(void);
                

Thursday, October 25, 2012

FINDING THE MINOR OF 3 X3 MATRIX IN C


//QUERIES ARE WELCOME AS COMMENTS
# include<stdio.h>
# include<conio.h>
#define C 3
int x = 0, y = 0;
void check(int a[][C], int b[][C-1], int c[][C], int m, int n);
void minor(int b[][C-1],int c[][C]);
void main()
{
int a[C][C], b[C-1][C-1], c[C][C], i ,j;
for(i = 0; i < C; i++)
{
for(j = 0; j < C; j++)
{
printf("ENTER YOUR ELEMENT AT %d X %d\n", i , j);
scanf("%d", &a[i][j]);
}
}
for(i = 0; i< C; i++)
{
for(j = 0; j < C; j++)
{
check(a, b, c, i,j);
}
}
for(i = 0; i < C; i ++)
{
for(j = 0; j < C; j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
}
void check(int a[][C], int b[][C-1], int c[][C], int m, int n)
{
int i, j, l = 0, k = 0;
for(i = 0; i< C; i++)
{
for(j = 0; j< C; j++)
{
if (i != m && j != n)
{
b[l][k++]  = a[i][j];
if(k == C-1)
{
l++;
k = 0;
}
}
}
}
minor(b, c);
}
void minor(int b[][C-1],int c[][C])
{
int z;
z = b[0][0] * b[1][1] - b[0][1] * b[1][0];
c[x][y++] = z;
if (y == C)
{
x++;
y = 0;
}
}

The Fibonacci Series In C Using Recurssion


//IN CASE OF DOUBT, COMMENT IT
# include<stdio.h>
int fibo(int n);
int r;
void main()
{
int i, j, k, l = 0;
scanf("%d",&j);
for(i = 0; i < j; i++)
{
for( k = 0; k <= i; k++)
{
l = fibo(k);
printf("%d ", l);
}
printf("\n");
}
}
int fibo(int n)
{
if(n == 0)
{
return (0);
}
else if(n == 1)
{
return (1);
}
else
{
r =  fibo(n- 1) + fibo(n-2);
return r;
}
}

Wednesday, October 24, 2012

MATRIX SOLVER-GAUSS JORDAN METHOD IN C


//KINDLY ASK THE DOUBTS IN COMMENTS
# include<stdio.h>

void subtrac(float b[][6], int k);

float constant(float c[][6], int a, int b);

void divide(float b[][6], int a, float c);

void main()

{

float a[3][6], k = 0.0;

int i, j;

for( i = 0 ;i < 3; i ++)

{

for( j = 0; j <  6; j++)

{

a[i][j] = 0;

}

}

for(j = 0; j < 3; j++)

{

for(i = 0; i < 3;i++)

{

printf("ENTER ELEMENT AT %d x %d\n",j, i);

scanf("%f", &a[j][i]);

}

}

a[0][3] = 1.0;

a[1][4] = 1.0;

a[2][5] = 1.0;

for(i = 0 ; i < 3; i++)

{

subtrac(a,i);

}

for(i = 0; i < 3; i++)

{

k = a[i][i];

divide(a, i, k);

}

for(i = 0 ; i < 3; i++)

{

for(j= 3; j < 6; j++)

{

printf("%f ", a[i][j]);

}

printf("\n");

}

}

void subtrac(float b[][6], int k)

{

int i, z;

float j;

for( i = 0; i < 3; i++)

{

if(i != k)

{

j = constant(b, i , k);

for(z = 0; z < 6; z++)

{

                         b[i][z] = b[i][z] - j * b[k][z];
 
}

printf("R%d -> R%d - (%.2f * R%d)\n",i+1,i+1,j,k+1);

}

}

}

float constant(float c[][6], int a, int b)

{

float con;

con = c[a][b]/ c[b][b];

return (con);

}

void divide(float b[][6], int a, float c)

{

int j;

for(j = 0; j < 6; j++)

{

b[a][j] = b[a][j] / c;

}

printf("R%d -> R%d / %.2f\n", a+1, a+1, c);

}

Tuesday, October 23, 2012

The N- Queens Problem in C


//FEEL FREE TO DROP ANY QUESTION IN THE COMMENTS
# include<stdio.h>
# include<conio.h>
# define C 8
int check(int k[][C], int m, int n);
void backtrack(int k[][C], int f2[], int m);
void increment(int k[][C], int m, int n);
void main()
{
int a[C][C] = {0},i, j = 0, c, fj[C] = {0}, z = 0, k, count = 0;
clrscr();
for(i = 0; i < C; i++)
{
reloop:
while(j < C)
{
c = check(a, i, j);
if(c == 0)
{
increment(a, i, j);
fj[i] = j;
z = 1;
break;
}
j++;
}
if(z != 1)
{
    backtrack(a, fj, i);
    j = fj[i - 1] + 1;
    i = i - 1;
    if(i < 0)
    {
goto end;
    }
    goto reloop;
}
j = 0;
z = 0;
if(i == (C-1))
{
for(k = 0; k < C; k++)
{
printf("(%d,%d);",k,fj[k]);
}
printf("\n");
getch();
count++;
backtrack(a, fj, i + 1);
j = fj[i] + 1;
    goto reloop;
}

}
end:
printf("%d",count);
getch();
}
int check(int k[][C], int m, int n)
{
int i, j, sum = 0;
for(i = 0; i < C; i++)
{
sum = sum + k[i][n] + k[m][i];
}
if(m == n)
{
for(i = 0; i < C; i++)
{
sum = sum + k[i][i];
}
}
else if(m < n)
{
for(i = 0, j = n - m; j < C; j++, i++)
{
sum = sum + k[i][j];
}
}
else if(m > n)
{
for( i = m - n, j = 0; i < C; i++,j++)
{
sum = sum + k[i][j];
}
}
if((m + n) == C-1)
{
for(i = C - 1, j = 0; j < C; j++, i--)
{
sum = sum + k[i][j];
}
}
else if((m + n) < C - 1)
{
for(i = m + n, j = 0; j <= m + n;  i--, j++)
{
sum = sum + k[i][j];
}
}
else if((m + n) > C-1)
{
for(i = C - 1, j = m + n - C + 1; j < C; i--,j++)
{
sum = sum + k[i][j];
}
}
return sum;
}
void increment(int k[][C], int m, int n)
{
k[m][n] = 1;
}
void backtrack(int k[][C], int f2[], int m)
{
int i, j;
i = m - 1;
j = f2[m-1];
k[i][j] = 0;
}