ash said:
i have got this question in old question papers and i know the answer
but didn`t understand how it is possible.
main( )
{
int x=0;
while(x<=50)
for( ;
if( ++x % 50 ==0)
break;
printf("x = %d", x);
}
the answer is 100.
if someone will explain, i will be thankful.
Perhaps the easiest way to see what's going on in a
case like this is to "play computer:" take pencil and
paper, write down the initial values of all the variables
that have them, and then follow the code line by line as
if you were the computer. Evaluate each expression or
test by consulting the variable values written on the paper,
and whenever a value changes scratch out the old and write
the new. Your mimicry would begin like this:
Set x to zero.
Is 0 <= 50? Yes, so the loop executes.
Change x from 0 to 1. Compute 1 % 50. Is that value
equal to zero? No, so the loop continues.
Change x from 1 to 2. Compute 2 % 50. Is that value
equal to zero? No, so the loop continues.
(At about this juncture you'll probably realize that
the inner loop will just keep executing until it has
advanced `x' to a multiple of fifty, so you'll just
write `x = 50' on your paper and forego simulating
all the rest of the loop. This kind of shortcut is
an important step in learning how to understand a
program: You are learning to replace rote simulation
with reasoning.)
Back to the outer loop, is 50 <= 50? Yes, so the
outer loop executes again.
...
After you have done this kind of low-level simulation
enough times with enough pieces of code, you will find that
you develop an ability to do without it. The shortcuts you
discover allow you to take a higher-level view of the code
than the one the computer itself takes; you begin to reason
about the code instead of following it without understanding.
On the other hand, you may also find that the higher-
level viewpoint is more likely to be decieved by constructs
that aren't quite what they seem: a `defaut' or `case1:' label
in a `switch' statement, a misleading indentation
if (a < 0)
printf ("Correcting a from %d to 0\n", a);
a = 0;
.... and so on. An eye for detail remains important in this
business.
double x[10][10];
int i, j;
/* Initialize x as an identity matrix: */
for (i = 0; i < 10; ++i) {
for (j = 0; j < 10; ++i)
x
[j] = (i == j);
}