Fiboccani Series.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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?
Last edited on
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<fstream>
#include<iostream>
#include<random>
#include<time.h>

using namespace 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;
}
}

Last edited on
AAAhhhhhh!! Thank you! :D
You can also solve this recursively.

Consider the following function.
1
2
3
4
5
6
7
unsigned long fibonacci(unsigned long 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.
This is based on the original code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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';          
    }
}
Last edited on
Topic archived. No new replies allowed.