in the following why the code num=num+1;can't be applied just after while loop in the beginning of curly braces? #include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { cout << "Number: " << num << endl; num = num + 1; } return 0; } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

in the following why the code num=num+1;can't be applied just after while loop in the beginning of curly braces? #include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { cout << "Number: " << num << endl; num = num + 1; } return 0; }

22nd Sep 2016, 2:48 PM
Prabhat Chandra Dwivedi
Prabhat Chandra Dwivedi - avatar
7 Answers
+ 6
Bcoz 1st it will print '1' as the print statement is before the increment and the after printing '1' it will check for the next line,from that line the loop start and with the increment of '1' i.e '2' it gets printed until false exibits.. Hope its helpful..
22nd Sep 2016, 9:13 PM
Junaid Ashraf
Junaid Ashraf - avatar
+ 5
Since the initial value to be printed is already been assigned to the variable here 'Num' which is 1 and since condition goes like O.k first print the init value of 'Num' and the increase it value by 1 (increment) that is Num=init(Num)+1... which is again stored in Num then new value of Num again increase and stored in as Num+1 (2+1=3) then 3 will be stored until it satisfies the While loop condition Range Viz..From int value (Already been decleared as 1) Upto Num less than 6 which is 5...
16th Oct 2016, 9:49 AM
Junaid Ashraf
Junaid Ashraf - avatar
+ 4
since its been already declared in the data type variable line that num will initiate from 1 i.e num =1, and then after that while loop will execute printing from 2 on...
23rd Sep 2016, 9:16 AM
Junaid Ashraf
Junaid Ashraf - avatar
+ 4
No it will not print from 2 to 6... loop exist withint the range of 2 to 5 since condition in (num<6) and not (num<=6) so it will execute upto less than 6 which is upto 5... so since 1 is init and upto less tha 6 so it will print from 1 upto 5... o.k.... i hope now its totally clear u.. if ny problm plz ask again we will try to help
23rd Sep 2016, 9:20 AM
Junaid Ashraf
Junaid Ashraf - avatar
+ 1
Well, you can, but that would print numbers from 2 to 6 instead of 1 to 5.
22nd Sep 2016, 3:23 PM
Zen
Zen - avatar
+ 1
There is no problem to increment first and then to execute the required statments but your result would change by skipping first value and would take the next value from the stream ...but there is no need to first giving the intial value and imidiately increment it in the first iteration ...
16th Oct 2016, 9:30 AM
Azeem Sarwar
Azeem Sarwar - avatar
0
why it will print from 2 to 6?when written in the beginning of curly braces
22nd Sep 2016, 10:04 PM
Prabhat Chandra Dwivedi
Prabhat Chandra Dwivedi - avatar