Home > C#, Interview Questions, Programming, Teasers, Tips & Tricks > C# Byte Iteration Question

C# Byte Iteration Question

This one is a great c# interview question – short and simple, but tricky.

static void Main(string[] args)
{
    for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
        Console.Write(b);
}

// A little tip
// byte.MinValue = 0
// byte.MaxValue = 255

How many times the above statement will be executed ?

VN:F [1.9.22_1171]
Rating: 4.4/5 (5 votes cast)
C# Byte Iteration Question, 4.4 out of 5 based on 5 ratings
  1. mmp
    July 10th, 2009 at 12:05 | #1

    256?

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  2. mmp
    July 10th, 2009 at 12:36 | #3

    endless loop?

    VA:F [1.9.22_1171]
    Rating: 4.0/5 (1 vote cast)
    • July 10th, 2009 at 12:57 | #4

      Correct :) And now the second part.
      What do you have to change to throw an overflow exception in the above code ?

      VN:F [1.9.22_1171]
      Rating: 0.0/5 (0 votes cast)
  3. Mio
    July 10th, 2009 at 12:53 | #5

    Forever…until you stop it or get out of memory exception :)

    VA:F [1.9.22_1171]
    Rating: 5.0/5 (1 vote cast)
  4. Joe Chung
    July 10th, 2009 at 13:38 | #6

    Put the for loop in a checked block.

    VA:F [1.9.22_1171]
    Rating: 5.0/5 (1 vote cast)
    • July 10th, 2009 at 13:52 | #7

      True

       
      checked {
          for (byte b = byte.MinValue; b < = byte.MaxValue; b++)
               Console.Write(b);
      }
      

      VN:F [1.9.22_1171]
      Rating: 0.0/5 (0 votes cast)
  5. mmp
    July 10th, 2009 at 13:43 | #8

    @Kossovsky Alexander
    Add “checked {}” expression? BTW thank you for reminding about this feature. It surely indicates that I have to refresh my knowledge on C# pecularities.

    VA:F [1.9.22_1171]
    Rating: 5.0/5 (1 vote cast)
    • July 10th, 2009 at 13:58 | #9

      That is what my blog is about. Reminding all of you (and my self) all the the stuff we shouldn’t forget

      VN:F [1.9.22_1171]
      Rating: 5.0/5 (1 vote cast)
  6. mmp
    July 10th, 2009 at 13:57 | #10

    @Mio
    Actually, you get an ‘out of memory’ exception not because of the ‘for’ structure itself, but because of Console.Write(b).

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  7. SjP
    July 29th, 2009 at 23:01 | #11

    @mmp
    Why does it produce the exception in the first place?

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  8. Ratkiia
    April 10th, 2011 at 00:08 | #12

    Why it is endless loop. Any explaination will help.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  9. Dan
    March 22nd, 2012 at 00:37 | #13

    Byte.MaxValue +1 = Byte.MinValue so the for never ends. For this not to happen you have to use checked{}.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  1. July 12th, 2009 at 10:51 | #1
  2. July 13th, 2009 at 02:32 | #2

Subscribe without commenting

SEO Powered by Platinum SEO from Techblissonline
watch free movies