Wednesday 28 January 2015

Preprocessor Statements #ifdef, #else, #endif


Consider the following C program



#define FIRST
int main()
{
    int x, y, z;
#ifdef FIRST
    x=2; y=6; z=4;
#else
    printf("Enter x:");
    scanf("%d", &x);
    printf("Enter y:");
    scanf("%d", &y);
    printf("Enter z:");
    scanf("%d", &z);
#endif

    printf(“x:%d\ny:%d\nz:%d”);
    return 0;
}


Note that if FIRST is defined using the #define, the values of x, y and z are hardcoded to values of 2, 6 and 4. When FIRST is defined, all that is passed to the compiler is the code between the #ifdef and the #else. The code between the #else and the #endif is not seen by the compiler and is simply ignored. It is as if it were all a comment.
Once you have your routine working, and desire to insert the printf and scanfs, all that is required is to go back and delete the the #define FIRST. Now, the compiler now ignores the following statements:

a=2; b=6; c=4;
but does see the printf and scanfs.


Quite often you will have code which doesn't work, but you really don't want to throw it away. I see many students doing this;
/*
unwanted code
*/
And this is acceptable. Of course a problem arises is you have a comment in the unwanted code.
Thus, it is better to do this

#ifdef OLD
     unwanted code
#endif 


Wednesday 14 January 2015

Disease and Diagnosis Example

THE TABLE GIVEN BELOW SHOWS THE HYPOTHETICAL TRAINING DATA FOR DISEASE DIAGNOSIS N=NO, Y=YES
Patient id#
Sore throat
Fever
Swollen Glands
congestion
Headache
Diagnosis
1
Y
Y
Y
Y
Y
Strep throat=1
2
N
N
N
Y
Y
Allergy=2
3
Y
Y
N
Y
N
Cold=3
4
Y
N
Y
N
N
Strep throat=1
5
N
Y
N
Y
N
Cold=3
6
N
N
N
Y
N
Allergy=2
7
N
N
Y
N
N
Strep throat=1
8
Y
N
N
Y
Y
Allergy=2
9
N
Y
N
Y
Y
Cold=3
10
Y
Y
N
N
Y
Cold=3

WRITE    A PROGRAM TO DISPLAY THE   DIAGNOSIS   WHEN USER ENTER THE SYMPTOMS OF A DISEASE BASED ON ABOVE GIVEN DATA.



#include<stdio.h>
#include<string.h>
int findDiagnosis(char**data,char *response,int *diagnosisNumber)
{
    int i,j,maxMatch=0,current_i,counter;
    for(i=0;i<10;i++)
    {
        counter=0;
        for(j=0;j<5;j++)
        {
            if(data[i][j]==response[j])
                counter++;
        }
        if(counter>maxMatch)
        {
            maxMatch=counter;
            current_i=i;
        }
    }
    return diagnosisNumber[current_i];
}

int main()
{
    int d;
    char data[10][5]={{'Y','Y','Y','Y','Y'},
    {'N','N','N','Y','Y'},
    {'Y','Y','N','Y','N'},
    {'Y','N','Y','N','N'},
    {'N','Y','N','Y','N'},
    {'N','N','N','Y','N'},
    {'N','N','Y','N','N'},
    {'Y','N','N','Y','Y'},
    {'N','Y','N','Y','Y'},
    {'Y','Y','N','N','Y'}};

    char diagnosis[3][20];
    char response[5];
    int diagnosisNumber[]={0,1,2,0,2,1,0,1,2,2};
    int i,j,maxMatch=0,current_i,counter;



    strcpy(diagnosis[0],"Strep Throat");
    strcpy(diagnosis[1],"Allergy");
    strcpy(diagnosis[2],"Cold");

    printf("Sore throat ? ");
    scanf(" %c",&response[0]);

    printf("Fever ? ");
    scanf(" %c",&response[1]);

    printf("Swollen Glands ? ");
    scanf(" %c",&response[2]);

    printf("congestion ? ");
    scanf(" %c",&response[3]);

    printf("Headache ? ");
    scanf(" %c",&response[4]);

    for(i=0;i<10;i++)
    {
        counter=0;
        for(j=0;j<5;j++)
        {
            if(data[i][j]==response[j])
                counter++;
        }
        if(counter>maxMatch)
        {
            maxMatch=counter;
            current_i=i;
        }
    }
    d=diagnosisNumber[current_i];

    printf("\n DIAGNOSIS : %s",diagnosis[d]);
    return 0;
}

Neural Network : Firing Rule


TABLE SHOWN BELOW DISPLAY THE    INPUT DATA   AND CORESSPONDING OUT DATA
APPLY THE FIRING RULE TO ABTAIN THE CORRECT TABLE USING. WE HAVE THE (0 TOUGHT SET) AND (1-TOUGHT SET)

X1:       0      0        0        0       1      1      1      1
X2:       0      0        1        1       0      0      1      1
X3:       0      1        0        1       0      1      0      1
OUT:      0      0       0/1      0/1     0/1     1     0/1     1

#include<stdio.h>
void print(int*arr,int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%d ",arr[i]);
    printf("\n\n");
}
int main()
{
    int i,j,counter,maxMatch,oneCount,zeroCount,current_j;
    int x1[]={0,0,0,0,1,1,1,1};
    int x2[]={0,0,1,1,0,0,1,1};
    int x3[]={0,1,0,1,0,1,0,1};

    int out[]={0,0,-1,-1,-1,1,-1,1};
    int newOut[8];

    for(i=0;i<8;i++)
        newOut[i]=out[i];
    for(i=0;i<8;i++)
    {
        counter=0;
        maxMatch=0;
        if(out[i]==-1)
        {
            for(j=0;j<8;j++)
            {
                counter=0;
                if(out[j]!=-1 && j!=i)
                {
                    if(x1[j]==x1[i])
                        counter++;
                    if(x2[j]==x2[i])
                        counter++;
                    if(x3[j]==x3[i])
                        counter++;
                }
                if(counter>maxMatch)
                    maxMatch=counter;
            }
            zeroCount=0;
            oneCount=0;
            for(j=0;j<8;j++)
            {
                counter=0;
                if(out[j]!=-1 && j!=i)
                {
                    if(x1[j]==x1[i])
                        counter++;
                    if(x2[j]==x2[i])
                        counter++;
                    if(x3[j]==x3[i])
                        counter++;

                    if(counter==maxMatch)
                    {
                        if(out[j]==0)
                            zeroCount++;
                        else if(out[j]==1)
                            oneCount++;
                    }
                }
            }
            if(zeroCount>oneCount)
                newOut[i]=0;
            else if(zeroCount<oneCount)
                newOut[i]=1;
            else
                newOut[i]=-1;
        }
    }
    printf("x1 : \n");
    print(x1,8);

    printf("x2 : \n");
    print(x2,8);

    printf("x3 : \n");
    print(x3,8);

    printf("old out : \n");
    print(out,8);

    printf("new out : \n");
    print(newOut,8);

    return 0;
}


Multi Point Cross Over using Bit Pattern

WRITE A PROGRAM TO DISPLAY MULTI POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRESENTATIONS

#include<stdio.h>

void printBitRepresentation(unsigned int parent, unsigned int crossOverPoint1,unsigned int crossOverPoint2)
{
    unsigned int num,i;
    num=1<<31;
    for(i=0;i<32;num>>=1,i++)
    {
        if(parent & num)
            printf("1");
        else
            printf("0");

        if(i==crossOverPoint1-1)
            printf(" | ");

        if(i==crossOverPoint2-1)
            printf(" | ");
    }
    printf("\n");
}
void printChildren(unsigned int parent1,unsigned int parent2,unsigned int crossOverPoint1,unsigned int crossOverPoint2)
{
    unsigned int num,i,a=0,b=0,c=0,d=0,e=0,f=0,child1,child2;
    num=1<<31;
    for(i=0;i<crossOverPoint1;num>>=1,i++)
    {
        if(parent1 & num)
            a+=num;
        if(parent2 & num)
            d+=num;
    }
    for(i=crossOverPoint1;i<crossOverPoint2;num>>=1,i++)
    {
        if(parent1 & num)
            b+=num;
        if(parent2 & num)
            e+=num;
    }
    for(i=crossOverPoint2;i<32;num>>=1,i++)
    {
        if(parent1 & num)
            c+=num;
        if(parent2 & num)
            f+=num;
    }
    child1=a+e+c;
    child2=d+b+f;
    printf("\n\nChild 1 = %u\n",child1);
    printf("Child 2 = %u\n",child2);

    printBitRepresentation(child1,crossOverPoint1,crossOverPoint2);
    printBitRepresentation(child2,crossOverPoint1,crossOverPoint2);

}
int main()
{
    unsigned int parent1,parent2,crossOverPoint1,crossOverPoint2;
    printf("Enter parent number 1 :");
    scanf("%d",&parent1);
    printf("Enter parent number 2 :");
    scanf("%d",&parent2);

    printf("Enter the Cross-Over point 1 [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint1);
    printf("Enter the Cross-Over point 2 [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint2);


    printf("\n\nBit representation for Parents is : \n");
    printBitRepresentation(parent1,crossOverPoint1,crossOverPoint2);
    printBitRepresentation(parent2,crossOverPoint1,crossOverPoint2);

    printChildren(parent1,parent2,crossOverPoint1,crossOverPoint2);
    return 0;
}


Single Point Cross Over using Bit Pattern

WRITE A PROGRAM TO DISPLAY SINGLE POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRESENTATIONS


/*
    WRITE A PROGRAM TO DISPLAY SINGLE POINT CROSSOVER USING BIT PATTERN AND ALSO USE THE GRAPHICAL REPRENTATIONS
*/

#include<stdio.h>

void printBitRepresentation(unsigned int parent, unsigned int crossOverPoint)
{
    unsigned int num,i;
    num=1<<31;
    for(i=0;i<32;num>>=1,i++)
    {
        if(parent & num)
            printf("1");
        else
            printf("0");

        if(i==crossOverPoint-1)
            printf(" | ");
    }
    printf("\n");
}
void printChildren(unsigned int parent1,unsigned int parent2,unsigned int crossOverPoint)
{
    unsigned int num,i,a=0,b=0,c=0,d=0,child1,child2,j;
    num=1<<31;
    for(i=0;i<crossOverPoint;num>>=1,i++)
    {
        if(parent1 & num)
            a+=num;
        if(parent2 & num)
            c+=num;
        if(i==crossOverPoint-1)
        {
            num>>=1;
            for(j=crossOverPoint;j<32;num>>=1,j++)
            {
                if(parent1 & num)
                    b+=num;
                if(parent2 & num)
                    d+=num;
            }
        }
    }

    child1=a+d;
    child2=c+b;
    printf("\n\nChild 1 = %u\n",child1);
    printf("Child 2 = %u\n",child2);

    printBitRepresentation(child1,crossOverPoint);
    printBitRepresentation(child2,crossOverPoint);
}
int main()
{
    unsigned int parent1,parent2,crossOverPoint;
    printf("Enter parent number 1 :");
    scanf("%u",&parent1);
    printf("Enter parent number 2 :");
    scanf("%u",&parent2);

    printf("Enter the Cross-Over point for single Point cross over [between 0 to 32]: \n");
    scanf("%d",&crossOverPoint);

    printf("\n\nBit representation for Parents is : \n");
    printBitRepresentation(parent1,crossOverPoint);
    printBitRepresentation(parent2,crossOverPoint);

    printChildren(parent1,parent2,crossOverPoint);
    return 0;
}


Saturday 10 January 2015

Expression Evaluation using Stacks (PostFix Technique) in C (Makefile)

header.h

long long int solveExpression(char *);
struct Node
{
 int data;
 char op;
 struct Node*next;
};
struct LinkedList
{
 struct Node*start; 
};
struct StackNode
{
 char op;
 struct StackNode*next;
};
struct Node*makeNode(int data,char op);
struct Node*insertAtEnd(struct Node*start, struct Node*newNode);
struct Node*deleteNode(struct Node*start,int data,char op);
void printList(struct Node*start);
struct StackNode*makeStackNode(char op);
struct StackNode*push(struct StackNode*top, struct StackNode*newNode);
struct StackNode*pop(struct StackNode**top);


LinkedList.c

#include"header.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
struct Node*makeNode(int data,char op)
{
 struct Node*newNode;
 newNode=(struct Node*)malloc(sizeof(struct Node*));
 newNode->data=data;
 newNode->op=op;
 newNode->next=NULL;
 return newNode;
}

struct Node*insertAtEnd(struct Node*start, struct Node*newNode)
{
 struct Node*currentNode;
 if(!start)
  return newNode;
 for(currentNode=start;currentNode->next;currentNode=currentNode->next);
 currentNode->next=newNode;
 return start;
}

struct Node*deleteNode(struct Node*start,int data,char op)
{
 struct Node*currentNode,*prevNode=NULL,*temp,*prev;
 for(prevNode=NULL,currentNode=start;;prevNode=currentNode,currentNode=currentNode->next)
 {
  if(currentNode->data==data && currentNode->op==op)
   break;
 }
 if(currentNode==start)
 {
  temp=start;
  start=start->next;
  free(temp);
 }
 else
 {
  prev->next=currentNode->next;
  free(currentNode);
 }
 return start;
}

void printList(struct Node*start)
{
 while(start)
 {
  if((start->op)!='\0')
   printf("%c\n",start->op);
  else
   printf("%d\n",start->data);
  start=start->next;
 }
 printf("\n");
}



LinkedListStack.c

#include"header.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
struct StackNode*makeStackNode(char op)
{
 struct StackNode*newNode;
 newNode=(struct StackNode*)malloc(sizeof(struct StackNode*));
 newNode->op=op;
 newNode->next=NULL;
 return newNode;
}

struct StackNode*push(struct StackNode*top, struct StackNode*newNode)
{
 if(!top)
  return newNode;
 newNode->next=top;
 return newNode;
}

struct StackNode*pop(struct StackNode**top)
{
 struct StackNode*returnNode;
 if(!(*top))
  return NULL;
 returnNode=(*top);
 *top=(*top)->next;
 return returnNode;
}



main.c

#include<string.h>
#include<stdio.h>
#include"header.h"

int main()
{
 char str[100000];
 printf("Enter the expression : ");
 scanf("%[^\n]s",str);
 
 printf("\nAnswer = %lld\n\n",solveExpression(str));
 return 0;
}



solveExpression.c

#include<stdio.h>
#include<stdlib.h>
#include"header.h"
int getPriority(char c)
{
 if(c=='(')
  return -1;
 if(c=='+' || c=='-')
  return 0;
 if(c=='*' || c=='/' || c=='%')
  return 1;
 if(c=='^')
  return 2;
}

struct LinkedList convertToPostfix(struct LinkedList infix)
{
 struct Node*infixNode;
 struct StackNode*top,*temp;
 struct LinkedList postfix;
 top=NULL;
 postfix.start=NULL;
 for(infixNode=infix.start;infixNode;infixNode=infixNode->next)
 {
  if(infixNode->op=='(')
  {
   top=push(top,makeStackNode(infixNode->op));
   continue;
  }
  if(infixNode->op==')')
  {
   while(top && top->op!='(')
   {
    temp=pop(&top);
    postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
   }
   pop(&top);
   continue; 
  }
  if(infixNode->op=='\0')
  {
   postfix.start=insertAtEnd(postfix.start,makeNode(infixNode->data,infixNode->op));
  }
  else
  {
   if(top==NULL)
    top=push(top,makeStackNode(infixNode->op));
   else
   {
    if(getPriority(infixNode->op)>getPriority(top->op))
    {
     top=push(top,makeStackNode(infixNode->op));
    }
    else
    {
     while(top && getPriority(infixNode->op) <= getPriority(top->op))
     {
      temp=pop(&top);
      postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
     }
     top=push(top,makeStackNode(infixNode->op));
    }
    
   }
  }
 }
 while(top)
 {
  temp=pop(&top);
  postfix.start=insertAtEnd(postfix.start,makeNode(-2147483647,temp->op));
 }
 return postfix;
}
int operate(int a,int b,char c)
{
 switch(c)
 {
  case '+':
   return a+b;
  case '-':
   return a-b;
  case '*':
   return a*b;
  case '/':
   return a/b;
  case '%':
   return a%b;
  case '^':
   return (a^b);
 }
 return 0;
}
long long int evaluate(struct LinkedList postfix)
{
 int answer;
 struct Node*ptr,*prev1,*prev2;
 while((postfix.start)->next)
 {
  for(ptr=postfix.start,prev1=NULL,prev2=NULL;ptr && ptr->op=='\0';prev1=prev2,prev2=ptr,ptr=ptr->next);
  answer=operate(prev1->data,prev2->data,ptr->op);
  prev1->data=answer;
  
  prev1->next=ptr->next;
  free(prev2);
  free(ptr);
 }
 return (postfix.start)->data;
}
long long int solveExpression(char str[])
{
 struct LinkedList infix,postfix;
 int i,num;
 infix.start=NULL;
 for(i=0;str[i];)
 {
  if(str[i]==' ')
  {
   i++;
   continue;
  }if(str[i]<='9' && str[i]>='0')
  {
   for(num=0;str[i] && str[i]<='9' && str[i]>='0';i++)
    num=num*10+str[i]-'0';
   infix.start=insertAtEnd(infix.start,makeNode(num,'\0'));
  }
  else
  {
   infix.start=insertAtEnd(infix.start,makeNode(-2147483647,str[i]));
   i++;
  }
 }
 postfix=convertToPostfix(infix);
 return evaluate(postfix);
}


Makefile

all: hello
hello: main.o solveExpression.o LinkedList.o LinkedListStack.o
 gcc main.o solveExpression.o LinkedList.o LinkedListStack.o -o hello
main.o: main.c
 gcc -c main.c
evaluateExpression.o: solveExpression.c
 gcc -c solveExpression.c
LinkedList.o: LinkedList.c
 gcc -c LinkedList.c
LinkedListStack.o: LinkedListStack.c
 gcc -c LinkedListStack.c