Help understanding simple limit to while loop

Can someone help me with the flow of this code.
So first user inputs the value lets say n=3. Then, in the its n--( post increment) which means the user value will be used first and then it will change the value of n. Is this true?
1
2
3
4
5
6
  int n;
	cout<<"Enter # of times you want to out put \"Hello World\": ";
	cin>>n;
	while(n-->0){
		cout<<"Hello world"<<endl;
	}


What would happen if it was --n?
Last edited on
Those things should be easy to test:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
int main ()
{
    int n = 3;
	while( n-->0){
		std::cout << n << " Hello world\n";
	}
	std::cout << n << " Hello\n";
	
    n = 3;
	while( --n>0){
		std::cout << n << " Hello world\n";
	}
	std::cout << n << " world\n";

	return 0;
}

What can you say based on the output?
@keskiverto Ohhh! Your way is better. I was thinking for a while and couldn't keep track. Thanx alot!
For future readers, here is my observation:

while(n-->0): In this, first the computer looks at n and then compares whether it is greater than 0; then lastly, n is decremented to 1. Then, the loop runs and goes on from there.

while (--n>0): In this, first n is decremented to 1 and then it compares if it is (new)n>0 then the loop will run.
Last edited on
Topic archived. No new replies allowed.