Print fibonacci numbers upto n

Giving correct output for 2 cases. Please help in resolving. Thanks. Given below is my code:
#include
using namespace std;
int main(){
long n, third;
cin>>n;
long first =0, second = 1;
cout<<first<<endl;
cout<<second<<endl;
third=first+second;
while(third<n){
cout<<third<<endl;

first = second;
second = third;
third = first + second;

}
return 0;
}

if n=0, your code will print both 0 and 1
either put a condition if n>=1 cout<<second
else instead of printing first and second seprately outside the loop, instead of cout<<third, do cout<<first in the loop

1 Like