0

# Depending where the increment line is, the output is different, could someone explain why? Much appreciated

https://code.sololearn.com/cEpkw20HZLxh/?ref=app

3rd May 2017, 5:06 PM
mdar
3 Antworten
+ 22
1st case: while (num < 6) { num = num + 3; cout << "Number: " << num << endl; } Output: 4 7 How it works: Initially num was 1. Inside the loop, the value is added with 3 first, then printed. So 1+3 = 4, then print it. Again, 4+3 = 7, then print it. 2nd case: while (num < 6) { cout << "Number: " << num << endl; num = num + 3; } Output: 1 4 How it works: Initially num was 1. Inside the loop, the value is printed first, then 3 has been added with last value. So num = 1, print 1, change num to 4 Again, num = 4, print 4, change num to 7. But since 7 makes the condition false, 7 won't be printed.
3rd May 2017, 5:57 PM
Shamima Yasmin
+ 5
in a "while loop" the compiler reads your cods from the beginning, so order is important.For example it does "num=num+3" first before it prints the integer, but in the second one it first prints the integer then does the "num=num+3".
3rd May 2017, 6:04 PM
keivan Ipchi
+ 2
in line 8 you add before output, in line 10 after output. so your output is shifted by one cycle. a) num = 1, compare, num=4, output, compare, num=7, output, compare, end b) num=1, compare, output, num=4, compare, output, num=7, compare, end
3rd May 2017, 6:00 PM
Volker Milbrandt