Can somebody explain this? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
0

Can somebody explain this?

int main() { int f=1, i = 2; while(++i<5) f*=i; cout << f; } (output is 12) If there is a nice soul out there whom would like to explain this as thoroughly as possible for me, it would be really appreciated. No matter how hard I try, I can't seem to get my head around it :S Espcially the while(++i<5) part. I don't understand the ++i<5 and how the output multiplied with f turns it into 12? as far as I understood this "int i" gets added up to 4(because can't go higher than 5), and then you multiply this with f which is 1*4??? or 2*4?? either way it doesn't make any sense that it turns into 12. :( As mentioned above, a thorough explenation would be very much appriciated. //A noob programer whos first language is C++.

16th Oct 2016, 10:35 PM
ye546
ye546 - avatar
2 ответов
+ 4
++i increments i, then evaluates it. The first time, i is incremented to 3, and we enter the loop because 3 is lower than 5. Inside the loop, we multiply f by i, so f is now 1*3=3. The second time, i is incremented to 4 and 4 is lower than 5, so we loop again. f is multiplied by i and is now 3*4=12. The third time, i is incremented to 5, and 5 is not lower than 5, so we exit the loop, and print the value of f, 12.
16th Oct 2016, 11:09 PM
Zen
Zen - avatar
0
Thanks a lot @Zen. This helped out big time, really appreciate it!
17th Oct 2016, 12:25 AM
ye546
ye546 - avatar