Examples of C part 46 calculate polynomial equation
Program :
Output:
Value of x
3
Enter order of polynomial
4
Enter coefficients of polynomial at x^0
1
Enter coefficients of polynomial at x^1
2
Enter coefficients of polynomial at x^2
5
Enter coefficients of polynomial at x^3
3.5
Enter coefficients of polynomial at x^4
3
3.00x^4+3.50x^3+5.00x^2+2.00x^1+1.00x^0=389.50Explanation:
Polynomial equation depends on order.For Ex. Order is 4.
Formula is: a4*x^4+a3*x^3+a2*x^2+a1*x^1+ a0*x^0
#include<stdio.h> #include<math.h> main() { float x,sum=0; int order,i; printf("Value of x\n"); scanf("%f",&x); printf("Enter order of polynomial\n"); scanf("%d",&order); float coefficient[order]; for(i=0;i<=order;i++) { printf("Enter coefficients of polynomial at x^%d\n",i); scanf("%f",&coefficient[i]); } for(i=0;i<=order;i++) { sum+=coefficient[i]*pow(x,i); } for(i=order;i>=0;i--) { if(i>0) printf("%.2fx^%d+",coefficient[i],i); else printf("%.2fx^%d=",coefficient[i],i); } printf("%.2f\n",sum); }
Value of x
3
Enter order of polynomial
4
Enter coefficients of polynomial at x^0
1
Enter coefficients of polynomial at x^1
2
Enter coefficients of polynomial at x^2
5
Enter coefficients of polynomial at x^3
3.5
Enter coefficients of polynomial at x^4
3
3.00x^4+3.50x^3+5.00x^2+2.00x^1+1.00x^0=389.50Explanation:
Polynomial equation depends on order.For Ex. Order is 4.
Formula is: a4*x^4+a3*x^3+a2*x^2+a1*x^1+ a0*x^0
- Variables used
- x → To store input from user
- order →To store the order of polynomial
- sum → To store output
- coefficient → To store coefficients like a1,a2...
printf("Value of x\n"); scanf("%f",&x); printf("Enter order of polynomial\n"); scanf("%d",&order); float coefficient[order];
Taking input from userfor(i=0;i<=order;i++) { printf("Enter coefficients of polynomial at x^%d\n",i); scanf("%f",&coefficient[i]); }
This loop is used to take coeffiecients one by one.As it iterates from 0 to order(say 4).So it takes coefficients of coefficients[0](i.e. a0)....to a4for(i=0;i<=order;i++) { sum+=coefficient[i]*pow(x,i); }
Now the loop iterates from 0 to 4 and sum=sum+coefficient[i]*x^i. which is equal to sum=sum+coefficient[0]*x^0+coefficient[1]*x^1+coefficient[2]*x^2+coefficient[3]*x^3+ coefficient[4]*x^4.As i traverse from 0 to 4for(i=order;i>=0;i--) { if(i>0) printf("%.2fx^%d+",coefficient[i],i); else printf("%.2fx^%d=",coefficient[i],i); } printf("%.2f\n",sum);
Here i will traverse from order to 0 which means 4 to 0. If i>0 then + symbol is added at the end of the coefficient i.e. coefficient*x^i+.
Else it won't add + at the end.- And finally sum will be printed after = symbol