Calculate for a given value X of the type float the numerical value of a polynomial of degree n: \(P(X) = A_nX^n + A_{n-1}X^{n-1}+ \cdots + A_1X + A_0\)

The values of n, coefficients \(A_n, \cdots , A_0\) and X will be entered on the keyboard and stored in a float array A of dimension $$n+1$$.

  • Use the pow() function for calculation.
  • Use the Horner scheme that avoids the exponentiation operations: \(P(X) = (( ( (A_n \times X + A_{n-1}) \times X + A_{n-2} ) \cdots  ) \times X + A_0 \)

 


Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <math.h>
main()
{
    	float A[20];
    	int I;      
    	int N;      
    	float X;   
    	float P;    

    	do{   
            printf("Entre the degree : ");
            scanf("%d", &N);
    	}while(N<0);
    
    	printf("Entre the value of X : ");
    	scanf("%f", &X);
    
    	for (I=0 ; I<N ; I++)
    	{
        	printf("Enter coefficient A%d : ", I);
        	scanf("%f", &A[I]);
    	}

	/* a) using pow
 	for (P=0.0, I=0 ; I<N ; I++)
       	P +=  A[I]*pow(X,I);      */
 
	 /* b) using Horner */
    	for (P=0.0, I=0 ; I<N ; I++)
        	P = P*X + A[I];
 
    	printf("Value for X = %.2f : %.2f\n", X, P);
    	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting by propagation (bubble sort)