Thursday, January 12, 2012

2.4b - Solved exercises with "for"


Ø       What does this fragment of code display?

for (i=1; i<4; i++) Console.Write("{0} ",i);

Answer: the numbers 1 to 3 (starts at 1 and repeats as long as it is less than 4).


Ø       What does this fragment of code display?

for (i=1; i>4; i++) Console.Write("{0} ",i);

Answer: I does not write anything, because the condition is false from the beginning.


Ø       What does this fragment of code display?

for (i=1; i<=4; i++); Console.Write("{0} ",i);

Answer: it shows a "5", because there is a semicolon after "for", so a blank command is repeated four times, and when it ends, "i" has the value 5.


Ø       What does this fragment of code display?

for (i=1; i<4; ) Console.Write("{0} ",i);

Answer: "1" continuously, because "i" is never increased, so the exit condition will never be will met.


Ø       What does this fragment of code display?

for (i=1; ; i++) Console.Write("{0} ",i);

Answer: write continually increasing numbers, starting at one and increasing one unit in each pass, but never ending.


Ø       What does this fragment of code display?

for ( i= 0 ; i<= 4 ; i++) {
    if ( i == 2 ) continue ;
    Console.Write("{0} ",i);
}

Answer: The numbers 0 through 4, except 2.


Ø       What does this fragment of code display?

for ( i= 0 ; i<= 4 ; i++) {
    if ( i == 2 ) break ;
    Console.Write("{0} ",i);
}

Answer: type the numbers 0 and 1 (it cuts in 2).


Ø       What does this fragment of code display?

for ( i= 0 ; i<= 4 ; i++) {
    if ( i == 10 ) continue ;
    Console.Write("{0} ",i);
}

Answer: the numbers 0 through 4, because the condition of "continue" is never met.


Ø       What does this fragment of code display?

for ( i= 0 ; i<= 4 ; i++)
    if ( i == 2 ) continue ;
    Console.Write("{0} ",i);

Answer: 5, because there are no brackets after "for", so only "if" command is repeated.

No comments:

Post a Comment