#include "stdafx.h"
#include <iostream>
int main(){
int x;
int y;
int z;
y = 1;
std::cin >> x;
for ( y = 1, z = 0; y+z < x;y++,z++){
y = y + z;
std::cout << y;
}
}
I think it's a mathematical error, but I don't know?
1st that's not correct for loop structure.
2nd your math is a bit cranky also.
First of all let's see what does the fibonacci sequence really is.
let's take the first 6 numbers:
1 1 2 3 5 8
2 is equal to 1 + 1. the 3rd number of the fibonacci sequence = 2nd + 1st. So the nth number equals to n-1 + n-2 numbers in the fibonacci sequence.
This can be done with a forloop the following way
#include<fstream>
#include<iostream>
#include<random>
#include<time.h>
usingnamespace std;
int main(){
int n;
cin>>n;
int a, b;
a = 0; //initialize the first 2 numbers
b = 1;
for (int i=0; i<n; i++){
cout<<a<<" "; //output a
int c;
c = a+b;
a = b; //a equals to be (next number) and b equals to c (next from the next number)
b = c;
}
}
unsignedlong fibonacci(unsignedlong number)
{
if ( (number == 0 || (number ==1) ) // base cases
return number;
else // recursion step
return fibonacci( number - 1 ) + ( fibonacci( number - 2);
}
This gets the same thing accomplished, although it does cause an explosive amount of function calls, thus increasing overhead.
Fibonacci is just a good example of using recursion, so I thought I would add it to the discussion.
@brownflower
I also considered using a recursive function to show him how it's done, but then, judging from his C++ level, I thought it would be better if he was given the for loop example first to understand better.
#include <iostream>
int main()
{
int x;
int y;
int z;
int temp;
std::cin >> x;
for (y = 1, z = 0; y < x; temp = y + z, z=y, y=temp)
{
std::cout << y << '\n';
}
}