Question:
Write a C program for the following?
Shubhangi
2012-10-05 05:41:10 UTC
.
WAP to calculate the following expression.
x=1+x+ (x^2) /2! + (x^3)/ 3! +........n for this expression calculate the factorial.
Without Recursive Function

I know how to solve recursive but dont know about without recursive.
Five answers:
2012-10-05 06:17:11 UTC
It would be absolutely moronic to use recursion in this case.



1= (x^0)/0!

x = (x^1)/1!



Substitute those into your expression; and you'll see that a simple for-loop suffices. Note that when you're calculating n!, you already know (n-1)! because you calculated that in the previous iteration.



### EDIT ### Anas Imtiaz is wrong at points 7 and 8: you don't need to write a function for factorial because (as I wrote, above) you get it practically for free if you use a for-loop. You also don't need to write a function to calculate power, because pow() is a math.h function. It's not smart to reinvent the wheel.
Anas Imtiaz
2012-10-05 06:15:48 UTC
Here is an algorithm:

1- Read x

2- Read n

3- Declare counter and initialize it to zero

4- Declare sum and initialize it to zero

5- Use a loop to iterate until counter is equal to n

6- in the loop, write an appropriate expression that can be used in every iteration

7- Write a function to calculate factorial

8- Write a function to calculate power

9- Use both these functions in your expression (the one in the loop)

10- In each iteration, add the result of the expression to sum

11- Display result
Jake_AUS :)
2012-10-05 05:48:26 UTC
I am assuming they want you to write the program assuming the maths() what ever functions is inaccessible?



o/w not sure your question sorry
TheMadProfessor
2012-10-05 06:36:02 UTC
int factorial (int n) {

if (n < 0) {return -1}

factorial = 1

for (i = 2; i <= n; i++;) {factorial *= i;}

return factorial;

}
2012-10-05 06:31:29 UTC
#include



static int factorial(int n)

{

        int r;



        for (r = 1; n; r *= n--)

                ;

        return r;

}



static int power(int b, int e)

{

        int r;



        for (r = 1; e--; r *= b)

                ;

        return r;

}



static double f(int x, int n)

{

        double r;



        for (r = 1; n; n--)

                r += (double) power(x, n) / factorial(n);

        return r;

}



int main(void)

{

        printf("%f\n", f(123, 4));

        return 0;

}



edit: With an optimisation described by jaco:



double f(int x, int n)

{

        int fac = 1, power = 1, i;

        double r = 1;



        for (i = 1; i <= n; i++) {

                fac *= i;

                power *= x;

                r += (double) power / fac;

        }

        return r;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...