ADVERTISEMENT
ADVERTISEMENT

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

ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.