Jump to content

Finding the Largest array

gurvinder.singh's Photo
Posted Jan 10 2013 02:03 PM

var foo = [1,20,254],i, largest= foo[0];

for(i=1; i<foo.length; i++){
largest = foo[i];
document.write( "<br /> " +"Largest no is: " + largest);

Hi I Just started programming and write a very small code that is to find the largest value in an Array I want to know the working of this code,The code is working fine for me but actually I want to know how this code work.Mainly i'm confused in largest=foo[0] variable that i declare above.

1 Subscribe

2 Replies

  macnlos's Photo
Posted Jan 11 2013 11:19 AM

The first line declares three variables:
  • foo is an array with a length of 3, and values 1, 20 and 254.
  • i is a variable
  • largest is a variable and it's value is set to the value of the first element in the FOO array, which is 1

If you think about this logically you need to compare the first element in the array to the next one. Whichever is largest is carried on and compared to the next element. You do this until there are no more elements and at the end you have the largest value.
Sent to you from my
iPad, iPhone, BlackBerry,
Laptop, Desktop, or
Kitchen Toaster
  shahidsaif's Photo
Posted Jan 12 2013 12:31 AM

hello sir, i am new here i do not know about the erray. but now i am learning to the erray. soon i will come back and give u the erray knowledge. okey. thnaks