# Thread: Issue with Horner's polynomial c program

1. ## Issue with Horner's polynomial c program

Code:
```#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)
{
if(count!=n)
{
count++;
printf("%d+%d*(",count-1,x);
return (count-1 + x*horner(n,x));
}
else
{
printf("%d))=",count);
return count;

}

}```
Can anybody help me in finding the issues with above program of evaluating a polynomial with horner's rule? I think the program is correct but it shows errornous output

2. Additional Info: this program uses Recursive mechanism. 'n' is the order of polynomial.

3. You may get a hint just by looking at your output. If I type "4 1", I'm looking for
Code:
`(((0*1+1)*1+2)*1+3)*1+4`
Code:
`0+1*(1+1*(2+1*(3+1*(4))`
Notice how your + and * are in the wrong place, and you've got your grouping going the wrong way.

4. Originally Posted by tabstop
You may get a hint just by looking at your output. If I type "4 1", I'm looking for
Code:
`(((0*1+1)*1+2)*1+3)*1+4`
Code:
`0+1*(1+1*(2+1*(3+1*(4))`
Notice how your + and * are in the wrong place, and you've got your grouping going the wrong way.
From the definition of Horner's Rule(Horner's Rule -- from Wolfram MathWorld), if I type "4 1", the output should be:
((((4)*1+3)*1 + 2)*1 +1)*1 +0
which is exactly the same (in reverse direction).
Thnx for considering.

5. Oh so you want the coefficients to go the other way. Well then, your answers are correct, or at least I've not been able to come up with one that isn't.

6. The issue with above problem is finally resolved.
It was the global variable "count" which was getting changed even before the original return expression was evaluated. Hence we take a local variable 'i' and store in it the instantaneous value of "count". Here is the solution:

Code:
```#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++;
return (i + x*horner(n,x));
}
else
{
return count;
}

}```
Thank you all for your valuable suggestion. And thank you Mr. Puneet Jindal for providing useful hint.