Home > Software design >  What is going on in this code. Can somebody explain me?
What is going on in this code. Can somebody explain me?

Time:09-29

Can please someone explain me what is going on with this code. I mean I don't get it. Here is the source code.

#include <iostream>
using namespace std;

int main(){
    int a = 0;
    int c = 0;
    for (int b = 1; b <= 144 ; b  ){
        a = b;
        b = c;
        c = a   b;
        
        cout << a << "\n";
    }
}

Output :

1
1
2
3
5
8
13
21
34
55
89
144

Thanks in advance!

CodePudding user response:

Well, I'll go by explaining it line by line.

Before main()

First, the include <iostream> imports the cout function to output to the terminal. The using namespace std; is like a shortener and imports the standard library. Instead of std::cout, now you are writing cout.

During main()

The int main() calls the main function of the file, which runs the program. The int keyword references that it should return an integer value. int a,c; references that you are declaring 2 variables, both integers, named a, and c.

The for loop has multiple parameters:

  • int b = 1; creates a variable that the for loop uses in its next arguments.
  • b <= 144; specifies that as b is being modified if it is less than or equal to 144 then the loop will continue to execute.
  • b means that for every iteration of the loop you will increase the value of b by one.

Here is an example of the first for loop iteration, with the b value filled in:

a = 1; // a is now 1
b = c; // c hasn't exactly been defined, but it is an integer
c = a   1; // or 1   0. c is now 2

In the next iteration, I will fill some more values in:

a = 1; // b is 1 and a is set to b
b = 1; // b is set to c
c = 1   1;

Now, why is b the same as the last iteration? Because c was technically 0, b was set to 0, and after the loop, it was increased by 1, so then it was back to 1. The only difference was that c was 1, which set the second iteration value of c to 2.

In the comments above, someone referenced this is the Fibonacci sequence which if you aren't aware about, it is an interesting topic to google.

  •  Tags:  
  • c
  • Related