Tuesday 31 January 2017

Evaluating Postfix expression using stack : C program

#include<stdio.h>
#define MAX 50
int stack[MAX];
int top=-1;
void push(int item)
{
if(top == MAX-1)
{
printf("stack is full");
return;
}
top=top+1;
stack[top]=item;
}

int pop()
{
if(top == -1)
{
printf("stack empty");
return;
}
int temp;
temp=stack[top];
top=top-1;
return temp;
}
main()
{
char ch;
int val,v3,v2,v1,i;
printf("enter the postfix expression\n At the end type #");
fflush(stdin);
scanf("%c",&ch);
while(ch != '#')
{
if(ch=='a' || ch == 'b'|| ch == 'c')
{
printf("enter the value of %c",ch);
scanf("%d",&val);
push(val);
}

if(ch == '+'||ch == '-'||ch == '*'||ch == '/')
{
v1=pop();
v2=pop();
switch(ch)
{
case '+': v3=v2+v1;
break;
case '-': v3=v2-v1;
break;
case '*': v3=v2*v1;
break;
case '/': v3=v2/v1;
break;
}
push(v3);
}
fflush(stdin);
scanf("%c",&ch);
}
val=pop();
printf("\nresultant is %d",val);
}





Infix to Postfix Conversion using stacks using Array. ONLY FOR EXPRESSIONS WITHOUT BRACKETS : C program

#include<stdio.h>
#define MAX 50
char stack[MAX];
int top=-1;

int preced(char ch)
{
 switch(ch)
 {
  case '+':
  case '-':
     return 1;
     break;
  case '*': 
  case '/':
     return 2;
     break;
  case '#':
     return 0;
     break;
  default:
     return 3;
 }
}

void push(char item)
{
 if(top == MAX-1)
 {
  printf("stack is full");
  return;
 }
 top=top+1;
 stack[top]=item;
}

void pop()
{
 if(top == -1)
 {
  printf("stack empty");
  return;
 }
 printf("%c",stack[top]);
 top=top-1;
}
main()
{
char ch;
push('#');
printf("enter the given infix expression\n At the end type #");
fflush(stdin);
scanf("%c",&ch);
while(ch != '#')
{
 while(preced(stack[top])>=preced(ch))
 {
  pop();
 }
 push(ch);
 scanf("%c",&ch);
}
while(stack[top]!= '#')
 pop();
}


Monday 30 January 2017

Implementing Stack using Linked List

#include <stdio.h>
#include <stdlib.h>
struct node
{
 int data;
 struct node *next;
};
struct node *top=NULL,*c,*p;
push()
{
 int val;
 printf("\nenter a value to insert into stack\n");
 scanf("%d",&val);
 struct node * newnode=malloc(sizeof(struct node));
 newnode->data=val;
 newnode->next = NULL;
 if(top == NULL)
  top = newnode;
 else
 {
  newnode->next=top;
  top=newnode;
 }
}
pop()
{
 if(top == NULL)
 {
  printf("\n Stack is EMPTY..Deletion is not possible");
  return;
 }
 printf("\n Deleted element = %d\n",top->data);
 c=top;
 top=top->next;
 free(c);
}
display()
{
 if(top == NULL)
 {
  printf("stack is empty");
  return;
 }
 else
 {
  for(c=top;c!=NULL;c=c->next)
   printf("%d\t",c->data);
 
 }
}
main()
{
 int opt;
  while(1)
 {
  printf("\nPress 1. Push\t 2. Pop\t3. Display \t4. Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
}
 }

}

Sum of array elements using recursion in C

What is a recursive solution to summing up a list of numbers? First you should note that the sum of [2 13 4 25 66 71 82 91]) is equal to 2 + sum of [ 13 4 25 66 71 82 91]

#include <stdio.h>
int sum(int *a,int index,int n)
{
if(index == n)
return 0;
return(a[index]+sum(a,index+1,n));
}
main()
{
int n,i,a[100];
printf("enter size of array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("array sum =%d",sum(a,0,n));
}

(OR)

#include <stdio.h>
int sum(int *a,int n)
{
if(n<=0)
return 0;
return(*a+sum(++a,--n));
}
main()
{
int n,i,a[100];
printf("enter size of array\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("array sum =%d",sum(a,n));
}


Write a C program to generate fibonacci series upto n terms using recursion
#include <stdio.h>
int fib(int n)
{
if(n == 0 || n ==1)
return n;
return(fib(n-1)+fib(n-2));
}
main()
{
int n,i;
printf("enter number of terms\n");
scanf("%d",&n);
for(i=0;i<n;i++)
printf("\n %d\t",fib(i));
}

Reversing every word in a given line of text: C program

Reversing every word in a given line of text
Program:
#include <stdio.h>
#include <string.h>
main()
{
char a[100],*token,st[10][50];
int i=0,j,l;
puts("enter line of text");
gets(a);
token = strtok(a," ");
while(token != NULL)
{
 strcpy(st[i],token);
 token=strtok(NULL," ");
 i++;
}
l=--i;
for(j=0;j<i;j++,i--)
{
     strcpy(a,st[j]);
     strcpy(st[j],st[i]);
     strcpy(st[i],a);
}
for(j=0;j<=l;j++)
 printf("\n%s",st[j]);

}

Sunday 29 January 2017

Recursive solution to Total number of sequences : C Program with Memoization

Write a recursive function to Find the total number of sequences of length n (using H and T) such that no two Hs are next to each other.

#include <stdio.h>
int a[20];
int total_seq(int n)
{
if(n == 1)
return 2;
if(n ==2)
return 3;
if(a[n]!=-1 )
return a[n];
a[n]=total_seq(n-1)+total_seq(n-2);
return a[n];
}
main()
{
int n,i;
printf("enter n value");
scanf("%d",&n);
for(i=0;i<20;i++)
a[i]=-1;
printf("\n Total number of sequences = %d",total_seq(n));
}


Maximum sum non-adjacent elements Recursive Solution: C program

Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.

#include<stdio.h>

/*Function to return max sum such that no two elements are adjacent */
int FindMaxSum(int *a, int index, int n)
{
  static int incl = a[0];
  static int excl = 0;
  int temp;
  if(index == n)
   return incl;
   else
   {
        temp=incl;
    if(incl<(excl+a[index]))
    incl=excl+a[index];
    excl = temp;
FindMaxSum(a,index+1,n);
   }
 
}
int main()
{
  int a[] = {5, 5, 10, 100, 10, 5};
  int size=sizeof(a)/sizeof(a[0]);
  printf("\nMaximum sum of non- adjacent elements= %d \n", FindMaxSum(a,1, size));
  return 0;
}

Thursday 26 January 2017

C Program to find a word is elfish or not using recursion

A word is considered elfish if it contains the letters: e, l, and f in it, in any order.
For example, we would say that the following words are elfish: white leaf, tasteful, unfriendly, and waffles, because they each contain those letters. Write a recursive function called elfish?  that, given a word, tells us if that word is elfish or not
Program:

#include <stdio.h>
#include <string.h>
int elfish(char *s,char *b, int i)
{
            if(b[i]=='\0')
                        return 1;
            if(strchr(s,b[i]))
                        return elfish(s,b,i+1);
            else
                        return 0;
}
main()
{
            char s[100],b[4]="elf";
            int result;
            printf("enter the string\n");
            gets(s);
            result=elfish(s,b,0);
            if(result ==0)
                        printf("given string is not elfish");
            else
                        printf("given string is elfish");
}

Output:

 

Monday 23 January 2017

C program to implement Ascending Priority Queue



Algorithm to insert a value in ascending priority queue:
Let head be a pointer that stores the address of first node
step 1: Read the value and its priority
step 2: create a new node using malloc function
step 3: Assign the value read to the data field of newnode (newnode -> data =value)
                                        and newnode -> pri = priority
step 4: store the address of node whose priority is > newnode priority in pointer c
step 5: store the address of node before c in pointer p
step 5: newnode –> next = p->next
step 6: p -> next = newnode



 Program


#include<stdio.h>
#include <stdlib.h>
struct node
{
            int data,pri;
            struct node *next;
};
struct node *head=NULL,*c,*p;
void create();
void display();
main()
{
            int n,i;
            printf("enter the number of elements");
            scanf("%d",&n);
            for(i=1;i<=n;i++)
                        create();
                        display();
}
void create()
{
            int v,priority;
            printf("enter value and priority\n");
            scanf("%d%d",&v,&priority);
            struct node *newnode = (struct node *)malloc(sizeof(struct node));
            newnode->data =v;
            newnode->pri=priority;
            newnode->next = NULL;
            if(head == NULL)
                        head = newnode;
            else if( newnode->pri < head->pri)
            {          
                        newnode->next=head;
                        head=newnode;
            }
            else
            {
                        c=head;
                        while(newnode->pri >=c->pri && c->next != NULL)
                        {
                                    p=c;
                                    c=c->next;
                        }
                        if(c->next == NULL && newnode->pri >= c->pri)
                        {
                                    c->next = newnode;
                        }
                        else
                        {
                                    p->next=newnode;
                                    newnode->next=c;
                        }
            }
}
void display()
{
            if(head == NULL)
                        printf("list is empty");
            else
            {
                        c=head;
                        while(c != NULL)
                        {
                                    printf("%d  %d->",c->data,c->pri);
                                    c=c->next;
                        }
            }
}





Sunday 22 January 2017

C program to Implement Queue using linked list

#include <stdio.h>

#include <stdlib.h>
struct Q
{

   int data;

   struct Q *next;

};



void enq(struct Q **,struct Q **);

void deq(struct Q **, struct Q **);

void display(struct Q *,struct Q *);

main()

{

     struct Q *front =NULL, *rear=NULL;

     int n,i;

     printf("enter the number of elements");

     scanf("%d",&n);

     for(i=1;i<=n;i++)

          enq(&front,&rear);

     display(front,rear);

     deq(&front,&rear);

     printf("\n After deleting one element\n");

     display(front,rear);

}

void enq(struct Q **front,struct Q **rear)

{

     int val;

     struct Q *newnode =(struct Q *)malloc(sizeof(struct Q));

     printf("enter a value");

     scanf("%d",&val);

     newnode->data=val;

     newnode->next=NULL;

     if(*front == NULL )

         *front = *rear = newnode;

     else

     {

         (*rear)->next=newnode;

         *rear=newnode;

     }

}



void display(struct Q *front,struct Q *rear)

{

        if(front == NULL)

              printf("queue empty");

        else

        {

              while(front != NULL)

              {

                    printf("%d->",front->data);

                    front=front->next;

              }

        }

}

void deq(struct Q **front, struct Q **rear)

{

          if(*front == NULL)

                printf("queue is empty");

          else

         {

                 if(*front == *rear)

                      *front = *rear = NULL;

                 else

                      *front=(*front)->next;

         }

}


Removing negative values in Queue : C program



#include <stdio.h>
#include <stdlib.h>
#define MAX 10
int queue[MAX],f=-1,r=-1;
void enq();
void deq();
void display();
void deletenegative();
main()
{
int n,i;
printf("enter the number of elements");
scanf("%d",&n);
for(i=1;i<=n;i++)
enq();
display();
printf("\nAfter deleting negative values\n");
deletenegative();
display();
}
void enq()
{
int val;
if(r==MAX-1) {
printf("Queue full");
return;
}
else if(f == -1 && r == -1)
f=r=0;
else
r=r+1;
printf("enter the data to be entered\n");
scanf("%d",&val);
queue[r]=val;
}
void deq()
{
if(f==-1)
{
printf("underflow");
return;
}
if(f ==r)
f=r=-1;
else
f=f+1;
}

void display()
{
int i;
if(f ==-1)
printf("queue empty\n");
else
{
for(i=f; i<=r;i++)
    printf("%d\t",queue[i]);
}
}
void move(int i)
{
for( ;i<r;i++)
queue[i]=queue[i+1];

}
void deletenegative()
{
int i;
if(f ==-1)
printf("queue empty\n");
else
{
for(i=f; i<=r;)
{
if(queue[i] <0)
{
if(i==f)
{
deq();
i=i+1;
}
else
{
move(i);
r=r-1;
i=i-1;
}
}
else
i=i+1;
}
}
}

Friday 20 January 2017

Array Implementation of circular queue using modulous operator : C Program

#include <stdio.h>

#include <stdlib.h>

#define MAX 5

int queue[MAX],f=-1,r=-1;

void enq();

void deq();

void display();

main()

{

 int n,i;

 printf("enter the number of elements");

 scanf("%d",&n);

 for(i=1;i<=n;i++)

  enq();

 display();

 printf("\nAfter one deletion queue elements are\n");

 deq();

 display();

}

void enq()
{

 int val;

 if(f == (r+1)%MAX)
 {
     printf("Queue full");
 }
 else 
 {
     if(f == -1 && r == -1)
        f=r=0;
     else
        r=(r+1)%MAX;

     printf("enter the data to be entered\n");

     scanf("%d",&val);

     queue[r]=val;
 }
}

void deq()
{

 if(f==-1)
       printf(" Queue is empty or underflow");
 else
 {
      printf("deleted element = %d",queue[f]);

      if(f ==r)

          f=r=-1;

      else

         f=(f+1)%MAX;
  }
}

void display()
{

int i;
if(f<=r)
{
   for(i=f; i<=r;i++)
          printf("%d\t",queue[i]);
}
else
{
   for(i=f;i<MAX;i++)
           printf("%d\t",queue[i]);
   for(i=0;i<=r;i++)
           printf("%d\t",queue[i]);
}
}



Output:


Thursday 19 January 2017

Implementing Circular Queue using Dynamic Memory Allocation

#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct Q
{
          int elements[MAX], front, rear;
};

void enq(struct Q *);
void display(struct Q *);
main()
{
int n,i;
struct Q *qptr=(struct Q *)malloc(sizeof(struct Q *));
qptr->front=-1;
qptr->rear=-1;
printf("enter the number of elements");
          scanf("%d",&n);
          for(i=1;i<=n;i++)
                    enq(qptr);
 display(qptr);
}
void enq(struct Q *qptr)
{
          int val;
 if((qptr->front == 0 && qptr->rear == MAX-1)||(qptr->front == qptr->rear+1))
          {
                   printf("Queue full");
                    return;
          }
          else if(qptr->front == -1 && qptr->rear == -1)
          {
                   qptr->front = 0;
                   qptr->rear=0;
 }
 else if(qptr->rear == MAX-1)
                   qptr->rear== 0;
 else
                   qptr->rear=qptr->rear+1;
printf("enter the data to be entered\n");
scanf("%d",&val);
qptr->elements[qptr->rear]=val;
}

void display(struct Q *qptr)
{
int i;
for(i=qptr->front;i<=qptr->rear;i++)
 printf("%d\t",qptr->elements[i]);
}




Output:

Wednesday 18 January 2017

Deleting first occurrence of a pattern in a given string without using strstr() :C program



#include <stdio.h>
#include <string.h>
main()
{
char T[30],P[30];
int i,k,l2,count,flag=0,j;
printf("enter a string");
scanf("%s",T);
printf("enter a pattern");
scanf("%s",P);
l2=strlen(P);
for(i=0;T[i]!='\0';i++)
{
if(T[i]==P[0]) // true only when the first character in pattern is in T
{
count=1;
for(k=i+1,j=1;P[j]!='\0';k++,j++)  // checks if remaining characters in P are in T
{
if(T[k]==P[j])
count++;
    else
        break;
}
if(count == l2) //if all the characters in P are in T then count = length of the pattern
{
flag=1;
break;
}
}
}
if(flag==1)
{
printf("\nPattern is first occured at %d\n",i);
while(T[i+l2]!= '\0')
{
T[i]=T[i+l2];
i++;
}
T[i]='\0';
printf("String after removing pattern=  %s",T);
}
else
printf("Pattern is not present in the given string");
}

OUTPUT:

Tuesday 17 January 2017

program to divide an image into blocks and count the 1's or edge information in the first row all blocks.

clear all;
close all;
I=imread('image_0001.png');
imNo=1;
grayI=rgb2gray(I);
[rows cols]=size(grayI);
edges=edge(grayI,'sobel');
sRow=floor(rows/6);
sCols=floor(cols/8);

for blockCount=1:8 % runs for each column
block=blockCount;
in(imNo,block)=0;
for j= 1:(2*sRow)  % inside the block to iterate through the  rows in the block
for k=(blockCount-1)*sCols+1: blockCount*sCols      % to iterate through columns
in(imNo,block)=in(imNo,block)+edges(j,k); % since edges contain 0's and 1's , only 1's will be added and so this will return the number of one's in each block
end
end
end

Monday 16 January 2017

Addition of two polynomials using linked list

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int coeff,exp;
    struct node *next;
};
struct node *create(struct node *head, int coe, int ex)
{
    struct node *c;
    struct node *new = (struct node *)malloc(sizeof(struct node));
    new->coeff=coe;
    new->exp=ex;
    new->next=NULL;
            if(head == NULL)
            {
                head=new;
               
            }
            else
            {
                c=head;
                while(c->next != NULL)
                    c=c->next;
                c->next=new;       
            }
return head;
}
display(struct node *head)
{
    struct node *c;
    if(head == NULL)
        printf("list is empty");
    else
    {
        for(c=head;c!=NULL;c=c->next)
                printf("%dx%d+ ",c->coeff,c->exp);
    }
}       
   
struct node *addpoly(struct node *p1, struct node *p2, struct node *head3)
{
    int x;
    while(p1 !=NULL && p2 !=NULL)
    {
        if(p1->exp == p2->exp)
        {
            x=p1->coeff+p2->coeff;
            if(x!=0)
            {
                head3=create(head3,x,p1->exp);
                p1=p1->next;
                p2=p2->next;
            }
        }
        else if(p1->exp>p2->exp)
        {
            head3=create(head3,p1->coeff,p1->exp);
            p1=p1->next;
        }
        else
        {
            head3=create(head3,p2->coeff,p2->exp);
            p2=p2->next;               
        }
    }
    while(p1 != NULL)
    {
        head3=create(head3,p1->coeff,p1->exp);
        p1=p1->next;
    }
    while(p2 != NULL)
    {
        head3=create(head3,p2->coeff,p2->exp);
        p2=p2->next;
    }   
    return head3;
}
main()
{
    struct node *head1=NULL,*head2=NULL,*head3=NULL;
    int coe,ex;
    printf("\nenter first polynomial");
    while(1)
    {
        printf("\n Enter -999 for coeff and -999 for exponent to exit\n");
        scanf("%d%d",&coe,&ex);
        if(coe != -999 || ex != -999)
            head1=create(head1,coe,ex);
        else
            break;
    }
    printf("\n Display first polynomial\n");
    display(head1);

    printf("\nenter second polynomial");
    while(1)
    {
        printf("\n Enter -999 for coeff and -999 for exponent to exit\n");
        scanf("%d%d",&coe,&ex);
        if(coe != -999 || ex != -999)
            head2=create(head2,coe,ex);
        else
            break;
    }
    printf("\n Display second polynomial\n");
    display(head2);
    head3=addpoly(head1,head2,head3);
   
    printf("\n Display resultant polynomial\n");
    display(head3);   
}


Output: