Monday, July 12, 2021

Junior Developer Central JS Practice Exercise - 13

 
Question: 

Write a Javascript program to check whether a given array of integers is sorted in ascending order. 




Answer: 

function isAscendingOrder (arr) {

for (let i = 0; i < arr.length; i++) {

if (arr[i+1] < arr[i]) return false;

} return true;

}



> we declare a function 'isAscending' 
> it has one parameter 'arr', which is an array of integers
> we have to check if this array of integers is sorted in ascending order or not
> so we use the for loop to check if each integer is greater than the following integer
> the for loop ensures that our check begins from the first integer to the last
> if the integer is greater than the following integer we return 'false' 
> because an array of ascending numbers, will have the preceding number lesser than the following number
> if that is not the case then we return 'true' once the for loop has finished the iteration and not found any number in the array which is greater than its following integer

No comments:

Post a Comment