C#

in C#
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);

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

• int[] arr ={4,6,1,12};
for (int i = 0; i <= ''; i++)

I dont believe this is correct. if you change it to the following:

int[] arr ={4,12,4,1};
for (int i = 0; i <= ''; i++)

then 4 is greater than 1 therefore 4 will replace 12?

if im correct above n have made another stupid mistake then it may be better to assign a variable to keep track of the first number aka 4. then compare the 2nd,3rd and 4th element in your array with it using ur IF loop. if you come accross a value greater than your variable (4) then replace it, otherwise just leave it alone n move to the next element.

im sorry but im new to this and im not sure what the else part of you loop would look like code wise.
• So '' is a character code for null and this is technically 0 - you want your loop to go through every element in your array and find the largest - so you want your for statement to look more like this:

for (int i = 0; i < arr.Length; i++)

This way the variable "i" will travel all the way from 0 to whatever the highest index in your array is. Traveling from 0 to 0 only makes the loop itterate once and doesn't even reach the value 12 to compare it.

I'm not sure what the point of the fancy if/else statement in there is, but if I were you I would simply rewrite this statement like so:

[code]
static void Main(string[] args)
{
int k = 0;
int[] arr = {4, 6, 1, 12};
foreach (int number in arr)
if (number > k)
k = number;

Console.WriteLine(k);
}
[/code]

the loop that I am using is called a "foreach" loop. And what this does is takes any array or collection and itterates through each of the items it contains. THis way you don't have to deal with counters and indexes and all that - you just say "Do this to each item in this array"

As a side note:
If you are confused why I didn't use brackets, any time you have a block-statement that only contains 1 line of code you can omitt the brackets. Another way to write the above code would be like so:

[code]
static void Main(string[] args)
{
int k = 0;
int[] arr = {4, 6, 1, 12};
foreach (int number in arr)
{
if (number > k)
{
k = number;
}
}

Console.WriteLine(k);