Program 1

Post date: Mar 26, 2013 5:23:03 AM

//Write two c++ functions one for factorial and another for power,

//then use these two functions to solve this equation : R=1!/n^1 + 3!/n^3 + 5!/n^5 …m!/n^m

#include<iostream>

using namespace std;

//Function power

float pow(int n, int m) //n,m: are function parameters

{

float p = 1; //p is storage and initialized by 1 because we have multiplication.

for(int i = 1; i <= m; i++) //our loop from 1 -> m.

p *= n; //multiply n by p and put the result in p.

return p; //return the value of p which is (n to power of m).

}

//Function factorial

float fact(int n) //n is function parameter

{

float f = 1; //f is storage and initialized by 1 because we have multiplication.

for(int i = 1; i <= n; i++) //our loop from 1 -> n.

f *= i; //multiply i by f and put the result in f.

return f; //return the value of f which is (factorial of n).

}

void main()

{

float sum=0, num1, num2; //sum is storage and initialized by 0 because we have addition.

cin >> num1 >> num2; //reading num1 then num2 variables.

for(int i = 1; i <= num1; i+=2) //our loop from 1 -> num1, its increased by 2 because we only want odd numbers in loop.

sum += //dividing factorial on power and store result in sum.

(fact(i) / //calling function fact(i), i: is function argument.

pow(num2, i)); //calling function pow(num2, i), num2,i: are function arguments.

cout << sum << endl; //printing sum (the result).

system("pause");

}