Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active December 27, 2015 19:15
Show Gist options
  • Save mmloveaa/3dd8311960e298af8977 to your computer and use it in GitHub Desktop.
Save mmloveaa/3dd8311960e298af8977 to your computer and use it in GitHub Desktop.
My solutions to Loops challenge
// 12/21/2015
//Use a while loop, a for loop, and a forEach loop to find the largest number in an array.
//Use the following array for each of these loops.
//[1,5,2,9,6,3]
----------------------------------------------------------------------------------------------------
//My while loop solution:
var max=0;
var i=0;
function largest(array){
while(i<array.length){
if(array[i]>max){
max=array[i];
}
i++;
}
return max;
}
largest([1,5,2,9,6,3]);
-----------------------------------------------------------------------------------------------------
//My do while loop solution:
var max=0;
var i=0;
function largest(array){
do{
if(array[i]>max){
max=array[i];
}
i++;
}
while(i<array.length)
return max;
}
largest([1,5,2,9,6,3]);
-------------------------------------------------------------------------------------
//My for loop solution
var max=0;
function largest(array){
for(var i=0; i<array.length;i++){
if(array[i]>max){
max=array[i]
}
}
return max;
}
largest([1,5,2,9,6,3]);
----------------------------------------------------------------------------------------
//My forEach solution
function largest(array){
var max=0;
array.forEach(function(element){
if(element>max){
max=element
}
})
return max
}
largest([1,5,2,9,6,3]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment