 Samyak Upadhyay - 4 years ago 132
C Question

# What is the difference between i++ in the if condition and i++ after the if inside a while loop?

``````int i = 0 ;
while(i < N)
{
char ptype ;
scanf("%c" , &ptype);
//getchar();
if(ptype == 'P'){
scanf("%d" , &passto);
//printf("\n");
preplayer = arr[top];
top++;
arr[top] = passto;
printf("%d\n", i);
i++;
}
if(ptype == 'B'){
int tempplayer = arr[top];
top++;
arr[top] = preplayer ;
preplayer = tempplayer;
i++;
}
//++i;
}
``````

And i++ not in if condition but before while:

``````int i = 0 ;
while(i < N)
{
char ptype ;
scanf("%c" , &ptype);
if(ptype == 'P'){
scanf("%d" , &passto);
//printf("\n");
preplayer = arr[top];
top++;
arr[top] = passto;
printf("%d\n", i);
//i++;
}
if(ptype == 'B'){
int tempplayer = arr[top];
top++;
arr[top] = preplayer ;
preplayer = tempplayer;
//i++;
}
i++;
}
``````

Both of them gives the different results.
Assume other variables are defined above the code like N = 10; and other integers and characters are also defined.

The above two codes give different results in the case of below input:

``````1
10 23
P 86
P 63
P 60
B
P 47
B
P 99
P 9
B
B
`````` Ambrish Pathak
Answer Source

First case:

inside if condition i++ will increment by one on every iteration of while loop if ptype is equal to p and again it will be incremented by one if ptype is equal to B so, total increment on i will be 2 (1+1)

Second Case:

i++ outside if but inside while: so i will get incremented by one on every iteration of while irrespective of if conditions. so, total increment on i will be 1 for each while iteration.

So, in first case i will get incremented two times if both 'if' conditions are met, while it will get incremented by one on every iteration of while loop one time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download