SETHA SITE INFORMATION

  • Increase font size
  • Default font size
  • Decrease font size

Calculate sum of Fibonacci in C++

E-mail Print PDF
The below code is to calculate the sum of Fibonacci (s=1+2+3+5+8+....).
Example:
if n=2 => s=1+2
if n=3 => s=1+2+3
if n=4 => s=1+2+3+5
if n=5 => s=1+2+3+5+8
.....................
long Fibonacci(int n)
{
	long s=0;
	int f1, f2, f;
	f1=1;
	f2=2;
	s=f1+f2;
	for(int i=3;i<=n;i++)
	{
		f=f1+f2;
		s+=f;
		f1=f2;
		f2=f;
	}
	return s;
}