Get benefited from interview Q/A and Online Test section. Subscribe to this blog to get updates directly in your mail box.
Best View in Google Crome, Mozilla firefox or IE 7 or above

Sunday, June 26, 2011

Find the Bugs in this C Sharp Dotnet Code

Here is another simple C Sharp dotnet interview question.

There is a piece of code in C# Dotnet as written below. The function takes a number array as input and returns the largest number. It has few bugs in it. Find out the bugs and fix them.

Code :

        public static int Largest(int[] list)
        {
            int max = int.MaxValue;

            for (int i = 0; i < list.Length - 1; i++)
                if (list[i] > max)
                    max = list[i];

            return max;
        }

You can post the answers as comments. Thank you.

3 comments:

  1. public static int Largest(int[] list)
    {
    int max = 0;
    for (int i = 0; i < list.Length; i++)
    if (list[i] > max)
    max = list[i];
    return max;
    }
    We cant use int.MaxValue as it gives the Maximum value itself and the condition always fails.
    We cant use list.Length-1 as the last element in the list will be ignored.

    ReplyDelete
  2. Hi Tayyaba,
    You are correct. Those are the two bugs in the code. Thank you for your response.

    ReplyDelete
  3. Actually initializing max with 0 is wrong, too. If you have only negative numbers in your list it will output 0.

    ReplyDelete

  © Blogger templates Shiny by Ourblogtemplates.com 2008

Back to TOP