I don't understand... output ans.. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I don't understand... output ans..

#include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { cout << "Number: " << num << endl; num = num + 3; } return 0; } out put Number 1: Number 4:

10th Jul 2016, 6:55 PM
meherDev
meherDev - avatar
4 Answers
+ 2
initially your num is declared as 1 and the condition inside the while loop is true i.e 1 < 6 so you get the first output as Number : 1... then again num + = 3 that is 1 + 3 = 4 then again it checks for the while condition 4< 6 or not , yes condition is satisfied then it prints the value as 4.. after again it adds 3 to the value of num , now the num is 7 it checks for the condition but this time condition is false and control comes out of the while loop and return 0 terminates the main function.. so thats how you get your ans as 1 and 4
16th Jul 2016, 4:51 AM
Karan Luther
Karan Luther - avatar
+ 1
Hi Mohammad, it's actually quite straightforward. You have a while loop that repeats *while* (-> hence the name) num is less than six. num is 1 before you enter the loop. with each loop iteration it's incremented by three until is not less than six anymore. Ergo num equals 1 in the first iteration until the instruction "num = num + 3" is executed and therefore num equals 1 when num is printed to the standard output (line cout << "Number....). The line "num = num + 3" increments num to be four (1+3). Then the precondition for executing the loop another time is checked. Four is less than six and therefore the statement block in the loop is executed again. Therefore, the line cout << "Number... prints four to the standard output. After this line the line "num = num + 3" is executed which increments num to seven (4+3). Seven is not less than six so the statement block in the loop will not be executed again and the program code after the loop is executed.
10th Jul 2016, 8:00 PM
Stefan
Stefan - avatar
+ 1
Hey Mohammad, you don't have to "sir" me. ;-)
10th Jul 2016, 8:08 PM
Stefan
Stefan - avatar
0
thank u stefan sir
10th Jul 2016, 8:03 PM
meherDev
meherDev - avatar