Confused about the while loop. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Confused about the while loop.

int num=3; while(num++ <10){ num+=2; } cout<<num; it outputs 13!??

24th Jul 2018, 11:39 AM
DiYiFan
DiYiFan - avatar
5 Answers
+ 1
num++ -> add +1 to the num at the end of the function (while, if, for,...) if(9++ <10){enter...} ++num -> add right now +1 and after check function values if(++9<10){no enter...}
24th Jul 2018, 12:19 PM
Yuri Biasi
Yuri Biasi - avatar
+ 1
Yes. The output would be 13. num++ adds 1 to num. You can test the code in the code playground. When you use num++ at the time it is used the value is the value of num. For example let's say the value of num is 4. When the while checks the function, the num values doesn't add up to 5. num++ stills shows 4. After the recall when num++ is done the value goes up. EXAMPLE: num = 0; num++; => still shows 0 print num => now shows 1 That is why the while loop would be run for 3 times. And the last time (4th time) when the loop is started, the functions adds 1 to num but as it is not less than 10 it doesn't do the other functions inside the loop. So the output would be 13.
24th Jul 2018, 11:57 AM
Mahdi Maymandi
+ 1
test it by using prints like below: #include <iostream> using namespace std; int main() { int num=3; cout<<num<<endl; while(num++ <10){ cout<<"before:"<<num<<endl; num+=2; cout<<"after:"<<num<<endl; } cout<<num; return 0; } after last print statement : after: 12 control again goes for condition check num++ < 10 and it will increment num by 1 so 12 becomes 13.
24th Jul 2018, 12:03 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
+ 1
//1st Step: int num=3; while(num++ <10){ num+=2; [3+2 = 5] } [5++ =6] cout<<num; //2nd Step while(num++ <10){ num+=2; [6+2 = 8] } [8++ =9] //3rd Step while(num++ <10){ num+=2; [9+2 = 11] } [11++ =12] //4th Step while(num++ <10){ [12 > 10, so go to the end of the while and do ++] num+=2; } [12++ = 13] cout<<num; [13]
24th Jul 2018, 12:11 PM
Yuri Biasi
Yuri Biasi - avatar
+ 1
๐Ÿ˜ŠSincerely appreciate your helping me. Thank all of you very much!
24th Jul 2018, 2:33 PM
DiYiFan
DiYiFan - avatar