//please can someone explain the output 4 8 12,why is it so? Thanks
int count = 0;
do
{
      for( int i = 0; i < 4; i++ )
              count++;
      cout << count << ‘ ‘;
} while ( count < 10 );
Member Avatar for 111100/11000

It's because for loop increments count by 4 each time
It's the same as if you wrote

int count = 0;
do
{

    count = count+4;
    cout << count << ‘ ‘;

} while ( count < 10 );
Member Avatar for 111100/11000

basically for loop runs
count++
4 times
because i < 4
and each time
count++ adds one number to previous value of count

Member Avatar for 111100/11000

and the reason why 12 is output is because do while loop first runs code
inside perentesis{} and only than checks whether to run through code again

Any more comments/explanations?

This is your code.

int count = 0;
do
{
      for( int i = 0; i < 4; i++ )
      { 
        count++;
      }

      cout << count << ‘ ‘;

} while ( count < 10 );

What's not clear about this?

if the while(count < 10),why is the 12 as output comes up and the counter is set to 0,why is the first output 4 and why does it gets incremented by 4,not by 1 (because of i++)

The for loop runs four iterations, so count gets incremented by one four times. count goes from 0 to 1 to 2 to 3 to 4, then is displayed. The while condition is still true, so the for loop executes again: 5,6,7,8, display.
While condition still true, so for loop goes again: 9, 10, 11, 12, display.

Now the while condition is false and the outer loop ends.

Thank you very much for very detailed explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.