Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#include using namespace std; int main() { int x = 123; cout << x % 10 << endl;

ID: 3680118 • Letter: #

Question

#include using namespace std;

int main() { int x = 123;

cout << x % 10 << endl; // line (a)

cout << x / 10 << endl; // line (b)

if (x > 50) cout << "Big" << endl; // line (c)

cout << endl;

while (x > 0) { cout << "1"; x /= 10;} // line (d)

cout << endl;

cout << x << endl; // line (e) }

Can someone explain whey the line (d) is printing 111?

And 11 when x=31 for

while (x > 0) { cout << "1"; x /= 10;} // line (d)

Thanks

Explanation / Answer

while (x > 0) { cout << "1"; x /= 10;} // line (d)

Loop 1:

while(x>0)                --> 123 > 0
{
cout << "1";              --> prints 1
x /= 10;                    --> x=123/10 => x=12
}

Loop 2:

while(x>0)                --> 12 > 0
{
cout << "1";      --> prints 1
x /= 10;                    --> x=12/10 => x=1
}

Loop 3:

while(x>0)   --> 1 > 0
{
cout << "1";              --> prints 1
x /= 10;                    --> x=1/10 => x=0
}

Hence, it stops executing while loop