Ask your own question, for FREE!
Computer Science 13 Online
OpenStudy (pratyush5):

Whats wrong in this program in C++ to print the fibonacci series ? #include #include void main() {clrscr(); int x=0,y=1,z,n=1; while(n<=20) {z=x+y; cout<

OpenStudy (lyrae):

In c++ you should only append .h for c headers not cpp headers. ``` #include<iostream> ``` main() is of type integer not void. ``` int main() ``` cout is a function in std. ``` std::cout ``` you set both x and y to same value in this step x=z,y=x; this is wrong.

OpenStudy (pratyush5):

Can you please write a corrected version ? Of the last part ? I'll understand better then :)

OpenStudy (woodrow73):

how does the << operator work?

OpenStudy (pratyush5):

That is a default for output

OpenStudy (woodrow73):

oh, so it outputs z each iteration?

OpenStudy (pratyush5):

Yup

OpenStudy (woodrow73):

if the y=x happens after the x = z, then y and x end up holding the same term number, instead of the highest 2 term numbers - then adding up x and y next iteration wouldn't give you the next term in the fibonacci sequence, just would equal 2*z.

OpenStudy (pratyush5):

Oh Oh ! So if I write y=x first and then x=z ? Will that be okay ?

OpenStudy (woodrow73):

should be in terms of algorithm :) though idk c++ syntax

OpenStudy (pratyush5):

Let me compile it that way.

OpenStudy (pratyush5):

IT WORKED

OpenStudy (pratyush5):

Thank you so much both of you :)

OpenStudy (woodrow73):

yw! does it make sense?

OpenStudy (pratyush5):

Yep it does :) Now that you have explained it, yes it does :)

OpenStudy (woodrow73):

ya, say you are holding y = 5 and x = 8, when you do z = x + z; z = 13, the next term in the sequence-- now you need x and y to reset to the term 13, and 8, so that when you add them next time, it will = the next term in the sequence. y = x will give y the term before 13 & x = z will give x the new highest term value of 13, but doing x = z first, will indeed set it equal to 13, but when you do y = x, you also get 13, and the addition of x & y next iteration will just be 13 * 2 ik I already said this, but just thought this looks much neater w/ examples & sitch.

OpenStudy (woodrow73):

And looks like Lyrae has some helpful tips for proper syntax ^^

OpenStudy (woodrow73):

Even if the program runs without making those changes, I'm sure there is good reason for them.

OpenStudy (lyrae):

http://ideone.com/1TwNIn

OpenStudy (pratyush5):

Thanks a lot :) @Lyrae

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!