The Gateway to Computer Science Excellence
+4 votes

The following program computes values of a mathematical function $f(x)$. Determine the form of $f(x)$.

main ()
    int m, n; float x, y, t;
    scanf ("%f%d", &x, &n);
    t = 1; y = 0; m = 1;
        t *= (-x/m);
        y += t;
    } while (m++ < n);
    printf ("The value of y is %f", y);
in Algorithms by | 545 views

3 Answers

+7 votes
Best answer
while(m++ < n)

here , we have used post-increment operator for variable $m$. So, first we will check whether $m<n$ is true or not then we will increase the value of '$m$' as $m=m+1$.

So, for $n=2$ , first we will go in the loop.

So, $t = 1*(\frac{-x}{1})$ and $y = 0 + (1*(\frac{-x}{1})) = \frac{-x}{1}$

Now, we will check the condition as :- $(1<2)$ . Since, it is true so we will go in the loop again as well as we will increment the value of $m$. So, now, $m=2$

Now again, in the body of the loop,

$t = (1*(\frac{-x}{1}))* (\frac{-x}{2})$ and $y = (1*(\frac{-x}{1})) + (1*(\frac{-x}{1})*(\frac{-x}{2})) = (-1)^{1}*\frac{x^{1}}{1} + (-1)^{2}*\frac{x^{2}}{1*2}$

Like this when we do then at certain point of time , we will check $((n-1) < n)$  or not for the value of $m=n-1$ . since it is true  . So, again we will go in the loop and increment in value of m.So, now , $m=n$

So, Now , $y = 0 + \frac{(-1)^{1}*(x^{1})}{1} + \frac{(-1)^{2}*x^{2}}{1*2} + \frac{(-1)^{3}*x^{3}}{1*2*3}+....+\frac{(-1)^{n}*x^{n}}{1*2*3*...*n}$ = $\sum_{i=1}^{n} \frac{ (-1)^{i}*x^{i}}{i!}$

Now again, we will check the condition. Since $(n<n)$ is false. So, we will not go in loop again and print the value of $y$ which is $\sum_{i=1}^{n} \frac{ (-1)^{i}*x^{i}}{i!}$
selected by
thanks @ankit gupta
Yes, It should be (-1)^i in the answer.
The value is closer to $(e^{-x}-1)$ since $\displaystyle e^{-x}=\sum_{i=0}^{\infty}\frac{(-1)^{i}x^{i}}{i!}$.

@techbd123 depends on $n$, whether it is small or large.  right ?

+3 votes
$t=1, y=0, m=1$

$t=t*\left ( -\left ( \frac{x}{m} \right ) \right )=1\times \left ( -\frac{x}{1} \right )$


for $m=2$

$t=t*\left ( -\left ( \frac{x}{m} \right ) \right )=\left ( -x \right )\times \left ( -\left ( \frac{x}{2} \right ) \right )=\frac{x^{2}}{2}$

$y=y+t=0-x+\left (\frac{ x^{2}}{2} \right )$

That is $e^{-x}-1$
+2 votes
The returned value is

$\sum_{i=1}^n (-1)^i \frac{x^i}{i!}$
explain plz

sir , I think it should be (-1)i in the above expression.


please tell me what is wrong in this

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
52,315 questions
60,426 answers
95,226 users