Can someone please explain this code!? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can someone please explain this code!?

"What is the output of the following code? int f = 1, i = 2; while (++ i < 5) { f* = i System.out.println(f); " I have copied this code from one of the quiz questions, and guessed the answer. The correct answer is 12. (I understand I have left out the closing curly brackets/braces ( } ), as i dont remember where they were in the question. 😜 So if anyone can help i would really appreciate it. Thanks in advance!! 👍🏻

14th Oct 2016, 7:47 PM
Rabia Sultan
Rabia Sultan  - avatar
20 Answers
+ 11
int f = 1, i = 2; while (++i < 5) { //increments i, then checks if it it lower than 5 f *= i; //multiplies f by i } System.out.println(f); //prints f The output of this code is 3*4 = 12.
14th Oct 2016, 7:55 PM
Zen
Zen - avatar
+ 11
@Ahmad: ++i increments i by 1, so when we do the first loop, i is already equal to 3. So f is multiplied by i and becomes 1*3=3. f *= i is a shorter synthax for f = f * i by the way.
17th Oct 2016, 5:17 PM
Zen
Zen - avatar
+ 7
int f = 1, i = 2; while (++i < 5) { //increments i, then checks if it it lower than 5 , so i=3 f *= i; //multiplies f by i (f=f*i) now f =1*3, therefore f=3 //then loop again executes as i=4,therefore f=3*4 } System.out.println(f); //prints f
13th Jun 2017, 6:58 PM
Nivetha
Nivetha - avatar
+ 4
3*4 =12 the last value for i is 4 as 5 is not less thann 5
3rd Feb 2018, 1:28 PM
YOSHITA
YOSHITA - avatar
+ 3
12
7th May 2018, 10:25 AM
abdiwahab jama said
abdiwahab jama said - avatar
+ 2
Thanks so much!! That totally makes sense now!! 😀👍🏻
14th Oct 2016, 7:58 PM
Rabia Sultan
Rabia Sultan  - avatar
+ 1
thanks all you are heros in C++
4th Jun 2020, 6:53 AM
Waled Moumari
Waled Moumari - avatar
0
Wait. How the f became three?
17th Oct 2016, 4:39 PM
Ahmad Ikmal
Ahmad Ikmal - avatar
0
thanks!
29th Nov 2017, 10:17 AM
Monika Devi
Monika Devi - avatar
0
int f = 1, i = 2; while (++ i < 5) { f = f*i; System.out.println(f); "
19th Dec 2017, 9:07 AM
Al Rafiul Hasan
Al Rafiul Hasan - avatar
0
12
14th Apr 2018, 11:51 AM
Osama
0
output is 12
25th Aug 2018, 3:05 PM
Lokesh M. Pincha
Lokesh M. Pincha - avatar
0
Why i execute to 4
23rd Dec 2018, 12:05 PM
Harish Sharma
Harish Sharma - avatar
0
Why we do 3*4 again
1st Jan 2020, 3:32 PM
Prikshit Choudhary Battan
Prikshit Choudhary Battan - avatar
0
youre welcome
4th Jun 2020, 7:11 AM
abdiwahab jama said
abdiwahab jama said - avatar
0
What is the output of the following code? int f=1, i=2; while(++i<5) { f*=i; } cout<<f; answer : 12
23rd Feb 2021, 7:34 AM
changa Hettiarachchi
changa Hettiarachchi - avatar
0
3 I--> 4 => 12 !!!
11th Mar 2021, 10:00 PM
Rusz Tamás
Rusz Tamás - avatar
0
12
1st Jan 2022, 12:38 PM
M.I.M.Aqueel
M.I.M.Aqueel - avatar
0
12
5th Jul 2022, 7:47 AM
Antenhe Yimer
0
12
8th Dec 2022, 12:08 PM
Prince Kumar
Prince Kumar - avatar