Click here to Skip to main content
14,932,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
#include<stdio.h>
int main ()
{

int i = 5;
while(i-- >=0)


printf("%d,",i);
i = 5;
printf("\n");
while(i-- >=0)
printf("%d,",i);
//break;
while (i-- >=0)
printf("%d,",i);

return 0;
}


What I have tried:

the output is coming
4,3,2,1,0,-1
4,3,2,1,0,-1

but ..I have coded for i-- >=0 ..so why it is showing till -1.
Posted
Updated 14-May-21 21:01pm
v2

Have a look at Increment/decrement operators - cppreference.com[^]

As you can see, you have used a post-increment operator so the comparison is done with the original (copied) value but the next line is executed using the decremented value.
   
Two things:
1) To add to what Wendelius says, this may help: Why does x = ++x + x++ give me the wrong answer?[^] - it doesn't exactly apply to your code, but it explains what the operators do, which may hep you understand why your code doesn't do what you expected.

2) Indent your code!
If you don't your code becomes mush harder to read, and that means you can make mistakes a lot easier.
C
#include<stdio.h>
int main ()
    {
    int i = 5;
    while(i-- >=0)
        printf("%d,",i);
    i = 5;
    printf("\n");
    while(i-- >=0)
    printf("%d,",i);
    //break;
    while (i-- >=0)
        printf("%d,",i);
    return 0;
    }
It's also a lot safer to always use curly brackets to delimit blocks:
C
#include<stdio.h>
int main ()
    {
    int i = 5;
    while(i-- >=0)
        {
        printf("%d,",i);
        }
    i = 5;
    printf("\n");
    while(i-- >=0)
        {
    printf("%d,",i);
        }
    //break;
    while (i-- >=0)
        {
        printf("%d,",i);
        }
    return 0;
    }
   
v2

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