Consider the following sequence:

\(\Big\{\begin{array}{c} U_0=1 \\ U_n=U_{n-1}+\frac{U_{n-1}}{n!} \texttt{ if } n>0\end{array}\)

  1. Write the function int Factorial (int n) that returns the factorial of an integer n.
  2. Write the function float Sequence(int n) that returns the value of Un defined in the above sequence and uses the function Factorial.
  3. Write a main function that asks the user to enter an integer n, calculates and prints the value of Un.

Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>

int factorial(int n)
{
	int i, fact=1;
	for(i=2; i<=n;i++)
		fact*=i;
	return fact;
}

float sequence(int n)
{
	int i;
	float u0=1, u1;
	for(i=1; i<=n;i++)
	{
		u1=u0+u0/factorial(i);
		u0=u1;
	}
	return u1;
}

void main()
{
	int n;
	do{
		printf("Enter n: ");
		scanf("%d", &n);
	}while(n<0);

	printf("Un=%f\n",sequence(n));
}






Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Asymptotic Analysis 13