Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

C#

rishabh29rishabh29 Member Posts: 2
static void Main(string[] args)
{
int k = 0;
int[] arr ={4,6,1,12};
for (int i = 0; i <= ''; i++)
{
if (arr[i] < arr[i + 1])
{
k = arr[i + 1];
}
else
{
k=arr[i];
}
}
System.Console.WriteLine(k);
System.Console.ReadLine();

i am trying to find largest number in this array
Although the code is Syntactically write but logically its wrong
the output i m getting is 6 instead of 12
can anybody explain me whats wrong with the logic

Comments

  • DataDinkDataDink Member Posts: 135
    There is some wonky stuffs going on with the posts here...
  • anthrax11anthrax11 Member Posts: 511
    First, the loop currently has only one iteration, because '' is zero. You need to check if "i < arr.Length". Second, you're not checking if k is already bigger than the next number in the array.

    A nice trick to use here is to replace the if statement with this:
    k = (arr[i] < arr[i + 1]) ? arr[i + 1] : arr[i];

    But a much simpler solution is to just check k against the number:
    [code]
    if (k < arr[i])
    k = arr[i];
    [/code]
    Hope you can put the pieces together now.

    Edit: dam, didn't notice the double post, but whatever..
Sign In or Register to comment.