Reputation: 9
I am trying to understand the output of this program. If I try to "translate" the code, I believe it should go like this:
How does the program prints it 4 times, how does the condition works here?
#include <stdio.h>
int main() {
int j = 0;
while(j++ < 3){
printf( "Ha ");
}
do{
j -= 2;
printf( "Hi ");
}
while(++j);
for(j = 1; j <= 3; j++){
printf( "Ho ");
}
printf("\n");
return 0;
}
The output is:
Ha Ha Ha Hi Hi Hi Hi Ho Ho Ho
Upvotes: 1
Views: 375
Reputation: 61
The best way to understand what your program does is to watch the value of j at each step of your program.
first j=0 then you enter into the while.
j=4
then you leave the while to enter into de do, while() statement. at this moment j=4.
in the do , while() :
at the end you enter in the for statement.
- ++x is called Pre incrementation (the variable is incremented before the expression evaluation)
- x++ is the post incrementation (the variable is incremented after the expression evaluation
- i'm not sure about this, you need to check this informations.
Upvotes: 0
Reputation: 67751
After first loop
j == 4
j -= 2 == 2
Hi
++j == 3
j -= 2 == 1
Hi
++j == 2
j -= 2 == 0
Hi
++j == 1
j -= 2 == -1
Hi
++j == 0 //end of th loop
Upvotes: 1
Reputation: 311058
After the first while loop
while(j++ < 3){
printf( "Ha ");
}
j is equal to 4.
So within the first iteration of the do-while loop
do{
j -= 2;
printf( "Hi ");
}
while(++j);
j is equal to 2. After the first iteration j is equal to 3. Within the second iteration j is equal to 1. After the second iteration j is equal to 2. Within the third iteration j is equal to 0. After the third iteration j is equal to 1. Within the forth iteration j is equal to -1. So in this forth iteration in the condition
while(++j);
j is equal to 0 and the control is passed to the next loop. So the do-while loop was executed 4 times.
That is the value of the postfix increment operator is the value of its operand before incrementing. And the value of the pre-increment operator is the value of its operand after incrementing.
Upvotes: 1
Reputation: 134366
The ++j
is prefix increment, i.e., the value will be increased and then, the incrased value will be used for the condition check.
I have added a print statement for the ease of understanding:
do{
j -= 2;
printf( "Hi ");
printf("value of j before the while = %d\n", j);
}
while(++j);
and the output is:
Hi value of j before the while = 2
Hi value of j before the while = 1
Hi value of j before the while = 0
Hi value of j before the while = -1
So, in the
while (++j)
, j
is 2
, and ++j
is 3
3-2 = 1
, and ++j
is 2.2-2 = 0
, and ++j
is 1.1-2 = -1
, and ++j
is 0 - this make the while
chec false and the loop ends.Upvotes: 1