0

How do you rewrite the following code using only 1 repetitive structure?

for(int i=1; i<=n; i++){while(j<i){r=2*b-a; a=b; b=r; j=j+1}s=s+b}

8th Nov 2021, 5:18 AM
Ropphy
Ropphy - avatar
3 odpowiedzi
+ 1
It would help to know how j is initialized (what are its possible starting values?). Also answer the same question for a, b, s and n.
8th Nov 2021, 6:04 AM
Brian
Brian - avatar
+ 1
oops, sorry messed up a little, actually it is: cin>>n; s=0; for(i=1; i<=n; i++){a=0; b=1; j=1; while(j<i){r=2*b-a; a=b; b=r; j=j+1} s=s+b} cout<<s;
8th Nov 2021, 9:17 AM
Ropphy
Ropphy - avatar
+ 1
The computation can be reduced to use only s and i in the for loop. To analyze, try inserting temporary cout statements to see the behavior of the variables - especially the outcome of b after the while loop.
8th Nov 2021, 3:13 PM
Brian
Brian - avatar