Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
int p=1;
do
{
printf("%d",p);
}
while(p--);

What I have tried:

int p=1;
do
{
printf("%d",p);
}
while(p--);
Posted
Updated 1-Oct-22 23:32pm

One could also write it much simpler and do everything with a for() loop:
C
for (int p=1; p >= 0; p--) {
	printf("%d", p);
}
 
Share this answer
 
p starts at 1.
You print the value of p, then check if it's zero.
If it isn't, you will go back around the loop.
But because you have a post-decrement on p before it actually makes the jump or not p is reduced by one.

It's the same thing as writing it like this:
C
#include <stdio.h>

int main()
    {
    int p=1;
    while (p >= 0)
        {
        printf("%d",p);
        p = p - 1;
        }
    return 0;
    }
This may help: Why Does x = ++x + x++ Give Me the Wrong Answer?[^] - it explains what the pre- and post- increment / decrement operators actually do.
 
Share this answer
 
Comments
KarstenK 2-Oct-22 4:55am    
wouldnt while(--p); do the job?
OriginalGriff 2-Oct-22 5:41am    
Nope: the current prints N to zero inclusive. Pre-decrement stops early!
KarstenK 3-Oct-22 3:30am    
Are you serious? Not in the original code with do-loop.
OriginalGriff 3-Oct-22 4:07am    
The original code was a do ... while
Run it, and see.
KarstenK 4-Oct-22 2:56am    
WTF??? Didnt expect that. Can you explain. Didnt help me at: https://en.cppreference.com/w/cpp/language/do

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900