why this code outputs 8? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why this code outputs 8?

int res=0; for (int i=1;i<10;i+=3){ if (10/i==2) //And if I add here "cout<<i; " to make more clear the logic, the result then became much different??? 40 continue; res+=i; } cout << res; //8 // I missed the closing bracket and added it.

19th Dec 2016, 9:47 PM
Boris Atanasov
Boris Atanasov - avatar
4 Answers
+ 2
you dont need brackets if your if statement only contains one line, yes it is good practice for those starting off to keep track of there code blocks but of you don't plan on adding logic to the statement the use of no brackets is acceptable for the continue statement
19th Dec 2016, 11:22 PM
Cory Clapp
Cory Clapp - avatar
+ 2
thank you for explaining.
20th Dec 2016, 4:12 PM
Boris Atanasov
Boris Atanasov - avatar
+ 1
well that code is missing one end bracket to make sense. And as you have No brackets for the if statement continue Will be executed every time if you insert another statement between if and continue.
19th Dec 2016, 10:04 PM
Mattias Eriksson
Mattias Eriksson - avatar
+ 1
Round#1: i=1, if false, res=1 Round#2: i=4, if true (10/4==2 for int) , res=1 Round#3: i=7, if false, res=8 Round#4: i=10, loop quits
19th Dec 2016, 10:06 PM
Ettienne Gilbert
Ettienne Gilbert - avatar