#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
void main()
{
int i,j;
i=3;
j=++i+--i;
printf("%d",j);
printf("%d",++i+--i);
getch();
}
output is 67
but see expression i have is same for both the statements then why answer is different
first printf statements o/p is 6
and second's is 7
please explain
Please explain the output of the c program?
I just compiled %26amp; ran it under Windows / Visual Studio 6, and it showed 66 as well. As the previous poster wrote: it's all compiler dependent. Which is exactly the reason why you shouldn't write code like that...
Reply:It is due to stacks.
Stack is just like you place books in a shelf
The book you put first will be in the bottom
and the last book will be at the top.
in the line "printf("%d",--i+ ++i);"
it is compiler from the right.
first i++ is done and placed in the stack(i.e 4)
then i-- is done and placed in the stack above it(i.e 3 (as i=4 now))
After that --i+ ++i is done and placed in the stack above it(i.e 7 (as 3+4))
I hope you understand what i say. If not mail to me(Gopinath M). My ID is(m_gopi_m@yahoo.co.in). I am new to programming and want to share some idea. so you can help me.
Here are some examples for stacks.
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
void main()
{
int i=5;
printf("\n %d %d %d",i,i++,--i);
getch();
}
This is another example mostly used to find the factorial of a number.
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
int factorial(int);
void main()
{
int num=5,fact;
fact=factorial(num);
printf("%d %d",num,fact);
getch();
}
int factorial(int a) /*factorial function(recurrsive function)*/
{
if(a==0 || a==1)
return(1);
else
return(a*factorial(a-1)); /*stack concept is used here*/
}
Reply:When run the same program in unix , the program out puted 66 , it is all compiler dependent.
Reply:The answer 67 is ok because you have given the expression i.e
j=++i+--i. Actually this is pre increment expression first of all j will be assigned to i i.e j=3+3 and then when you go to next printf statment then i=3 because first time ++i will be equal to 4 (after complition of ++i) then the value of i will be again 3 (after the complition of --i) and in the second printf statment the value of i=4(after the complition of ++i) then the value of i will be decresed by 1 and i will be equal to 3 (after the complition of i) and you have not written "\n" so it will be shown 67.
Good Question
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment