These two codes are logically same, but why the output is different in both case?
int sum(int x)
{
int s=0;
while(x--)
{
s=s+x;
}
return s;
}
AND
int sum(int x)
{
int s=0;
while(x!=0)
{
s=s+x;
x--;
}
return s;
}
These two codes are logically same, but why the output is different in both case?
int sum(int x)
{
int s=0;
while(x--)
{
s=s+x;
}
return s;
}
int sum(int x)
{
int s=0;
while(x!=0)
{
s=s+x;
x--;
}
return s;
}
while(x--)
For the first sum function, the x-- in this line means you are reducing the value of x by 1(x = x-1;). So, if the value of x was 5 then it will be reduced to 4 and we are then adding 4 to s.
In the second sum function if the value of x is 5, we are not reducing anything in start, we then add 5 to s and after that the value of x is reduced.
This is the difference between both.
agreed
In the first while loop the value of x is decremented before it’s added to x while in second one x was added first then decremented
@ayushkr07 is absolutely correct in earlier approach you are using post decrement in while loop where
firstly condition is checked to be true
post decrement of x will take place
now that updated value of x is added in s
but in second approach
firstly condition is checked to be true
now value of x is added in s
post decrement will take place
the only difference in result of both cases is that you will not able to add initial value of x in s in first one while in other you can
Hope you like my explaination @anon15081682