Help Simplify the following for loop

Hello all,
I've been given an excersize to simplify the following forloop but i think its already simplified, what are your thought, is there anything more i can do?

1
2
3
4
5
6
  for( int j = 2 ; j != n; j++ ) {
        c = b + a;
        a = b;
        b = c;
        cout << "Fibonacci (" << j + 1 << ") = " << c << endl;
    }


edit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

void fibonacci(int a, int b, int c, int n)
{
    cout << "Fibonacci (1) = 0" << endl;
    cout << "Fibonacci (2) = 1" << endl;

    //using an iterative approach for calculating
    //the n_th number in the series
    for( int j = 2 ; j != n; j++ ) {
        c = b + a;
        a = b;
        b = c;
        cout << "Fibonacci (" << j + 1 << ") = " << c << endl;
    }
}


int main()
{
    unsigned long a = 0, b = 1, c = 0, n = 0;

    cout << "How many Fibonacci numbers do you want to print?" <<endl;
    cin >> n;

    fibonacci(a,b,c,n);

    return 0;
}
Last edited on
Do you need all variables a, b and c?
If you Need All Variables then:


1
2
for( int j = 2 ; j != n; j++ )
    c = b + a, a = b, b = c, cout << " " << c << endl;



Done :)
Is simplicity measured in the number of statements you have? I don't think so.
please see edit, i have attached the full code.

The excersize was to remove any unnecesary declaration in the code, and to clean it of any flaws.

**i do need abc!
Line 7: The first Fibonacci number is considered to be F(0) = 0.
http://en.wikipedia.org/wiki/Fibbonaci_Series

Line 23, 28: There is no need to declare a,b,c as variables in main() or to pass a,b,c as arguments. a,b,c can be decalred as locals inside Fibonacci ().

Are you required to use an iterative algorithm? A recursive algorithm is shorter, but runs the risk of stack overflow for large values of n.

Instead of for( int j = 2 you could put for( int j = 0

That requires a little rearrangement of the code, but eliminates the need for these lines:
1
2
    cout << "Fibonacci (1) = 0" << endl;
    cout << "Fibonacci (2) = 1" << endl;
Last edited on
Topic archived. No new replies allowed.