C++ - Print Fibonacci Series of Numbers till N Terms using While in C++ Program.


IncludeHelp 14 August 2016

In this code snippet we will learn how to print Fibonacci Series till N terms using while? Number of terms will be read through keyboard and program will print series till given value.

In this program we will take two numbers initially (0 and 1) and read total terms (for example: 10) and run loop 8 times because two terms already we have.

C++ Code Snippet - Print Fibonacci Series till N Terms using while Loop

/*C++ - Print Fibonacci Series of Numbers 
till N Terms using While in C++ Program.*/

#include <iostream>
using namespace std;

int main(){ 

	int n1=0, n2=1;
	int sum=0;
	int terms,count=0;

	cout<<"Enter total temrs: ";
	cin>>terms;

	//display starting two numbers 0 1
	cout<<n1<<" "<<n2<<" ";

	while (count<(terms-2)){
		sum=n1+n2;    //sum of first and second number
		n1=n2; //assign second number in first variable
		n2=sum; //assign sum in second variable
		cout<<sum<<" "; //print sum
		count+=1;
	}

	cout<<endl;

	return 0;
}

    Enter total temrs: 10
    0 1 1 2 3 5 8 13 21 34



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.