How to use Loops In Javascript
The loops in JavaScript can be used to select the largest number from a set of digits. We are creating an empty variable to store the largest number, then we are repeatedly finding the largest digit in the set of digits, then we are adding this largest digit to the variable and retrieving it from the array of input digits.
Syntax:
while(condtion) {
//statements
for(condition) {
if(condition) {
//statements
}}}
Example: In this example, we will construct the largest number from digits using looping in JavaScript.
Javascript
let inputNumber = [8, 3, 4, 7, 9]; let largest = "" ; while (inputNumber.length > 0) { let largestDigit = -1; let largestDigitIndex = -1; for ( let i = 0; i < inputNumber.length; i++ ) { if ( inputNumber[i] >= largestDigit ) { largestDigit = inputNumber[i]; largestDigitIndex = i; } } largest += largestDigit.toString(); inputNumber.splice( largestDigitIndex, 1 ); } console.log(largest); |
Output
98743
JavaScript Program to Construct Largest Number from Digits
In this article, we have given a set of digits, and our task is to construct the largest number generated through the combination of these digits. Below is an example for a better understanding of the problem statement.
Example:
Input: arr[] = {4, 9, 2, 5, 0}
Output: Largest Number: 95420
Table of Content
- Using sort() Method
- Using Math.max Method
- Using Loops
- Using Array
Contact Us