Thursday 4 February 2016

Evaluating a Polynomial (Programming Assignment )

You are given a polynomial of degree n. The polynomial is of the form P(x) = anxn + an-1xn-1 + … + a0, where the ai‘s are the coefficients.  Given an integer x, write a program that will evaluate P(x).


You are provided with a function named power( ) that takes two positive integers x & y and returns xy. If y is 0, the function returns 1.


The prototype of this function is


int power(int x, int y);
You do not have to write the program for power ( ) function. This function is automatically added at the end of the code segment that you write.
INPUT: Line 1 contains the integers n and x separated by whitespace.

Line 2 contains the coefficients an, an-1…, a0 separated by whitespace.


OUTPUT: A single integer which is P(x).
CONSTRAINTS: The inputs will satisfy the following properties. It is not necessary to validate the inputs.
1 <= n <= 10 1 <= x <= 10
0 <= ai <=10


Solution-:


#include<stdio.h> /* function to calculate power x^y */ int power(int x, int y){ int pow=1; while (y!=0){ pow*=x; y--; } return pow; } int main() {long int p=0;int x,n,a[10],i; scanf("%d%d",&n,&x); for(i=0;i<=n;i++) {scanf("%d",&a[i]); p=a[i]*power(x,n-i)+p;} printf("%ld",p); return 0; }

6 comments:

  1. Replies
    1. Shankar Sir strictly ordered not to post solution before deadline.
      Try it yourself , if you encounter any problem i will readily help you.
      even you want logic i can explain it also. please try yourself first.

      Delete
  2. what should i do if i get a presentation error?

    ReplyDelete
    Replies
    1. what presentation error you are getting .can you show me the screenshot of error

      Delete
  3. DO nothing.There is no chance to get a presentation error in this program.

    ReplyDelete

  4. Very informative article.Thank you author for posting this kind of article .


    http://www.wikitechy.com/view-article/power-function-in-c-with-example-and-explanation



    Both are really good,
    Cheers,
    Venkat

    ReplyDelete