Wednesday, June 22, 2011

C program to evaluate a polynomial using HORNER’s Rule

Recently I was going through Data Structures in C, and I came to the problem of evaluating a polynomial using Horner’s rule. Horner’s rule is a strategy for evaluating a polynomial A(x) at a point using a minimum number of multiplication.

The following C program is a correct one, but the thing I want to emphasize is trouble with the use of global variables. Lets go through the C code first:
#include<stdio.h>
#include<conio.h>
int horner(int,int);
int count=0;
void main()
{
     /*Horner's rule for evaluating a polynomial */
     /* let us take a0=0,a1=1,a2=2.. and so on */
    
     int n,x,h=0; //n is order, x is value of X in polynomial.
     scanf("%d %d",&n,&x);
     h=horner(n,x);
     printf("%d",h);
     getch();
}

int horner(int n, int x)
{
    int i;
    if(count!=n)
    {
                i=count;
                count++;
                printf("%d+%d*(",i,x);
                return (i + x*horner(n,x));
    }
    else
    {
        printf("%d))=",count);
    return count;
   
}
    
}
Initially I faced a big problem with the above program when I was not using the local variable ‘i’ in the ‘horner’ function. You can check the output with and without the use of ‘i’. The problem was that all the return statements were being evaluated after the last ‘horner’ got evaluated for the recursive function, and in the meanwhile, the global variable ‘count’ got changed every time ‘horner’ was evaluated. Since the return statement depends upon ‘count’, the output came out to be deviated from the expected value depending upon the size of input. Hence the variable ‘i’ came into existence.

1 comment:

  1. Thanks Dear ,

    I helped us a lot.

    Keep posting such kind of programs. Our best wishes with you.

    ReplyDelete