JS Loops

HTML
CSS
C#
SQL

Loops

Loops are essential constructs in programming that enable the repetitive execution of a set of instructions. They provide a mechanism to iterate over a block of code multiple times, making it possible to automate tasks, process data, and streamline the execution of algorithms. In most programming languages, including JavaScript, several types of loops are commonly employed to cater to different scenarios.

1. while Loop:

The `while` loop repeatedly executes a block of code as long as a specified condition evaluates to true. The condition is checked before each iteration.

Example:

In this example, the loop will run five times, printing the current iteration number.

2. do...while Loop:

The do…while loop is similar to while, but it guarantees the execution of the block of code at least once, as the condition is checked after the first iteration.

Example:

This loop will also run five times, but it ensures the block executes at least once.

3. for Loop:

The `for` loop is designed for iterating a specific number of times. It includes an initialization, a condition, and an increment/decrement expression.

Example

This loop achieves the same result as the previous examples but in a more compact form.

4. for...in Loop:

 The `for…in` loop iterates over the properties of an object. It is particularly useful for working with object properties.

Example:

 This loop prints each property and its corresponding value in the `person` object.

5. for...of Loop:

The `for…of` loop is used to iterate over the values of iterable objects like arrays or strings.

Example:

This loop outputs each color in the `colors` array.

6. Nested Loop

Nested loops are loops within loops, allowing for more intricate control flow.

Example:

In this example, there’s an outer loop that runs three times, and within each iteration of the outer loop, there’s an inner loop that runs twice. This results in a total of six iterations (3 outer * 2 inner). Nested loops are powerful for handling complex patterns and multidimensional data structures.

Loops are fundamental tools for creating efficient and scalable programs. Choosing the right type of loop depends on the specific requirements of a task and the nature of the data being processed. Understanding and mastering loops is crucial for any programmer seeking to build robust and dynamic software solutions.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a program in which the user takes five numbers using a prompt by loop then stores and iterates over an array of numbers and prints out only the numbers that are divisible by 3.

The task is to create a simple program where the user inputs five numbers, and then the program stores and iterates over those numbers. It prints out only the numbers that are divisible by 3.
1. User Input:
The program prompts the user to enter five numbers. This is done using a loop, likely a for loop, to iterate five times and ask the user for each number.
2. Store Numbers:
The program stores the entered numbers in an array. An array is like a list that can hold multiple values.
3. Iterate Over Numbers:
The program goes through each number in the array (using a loop) and checks if it’s divisible by 3.
4. Print Divisible Numbers:
If a number is divisible by 3, it prints that number.
Example:
If the user enters the numbers 9, 12, 5, 6, and 18.
– The program stores these numbers in an array: [9, 12, 5, 6, 18].
– It then checks each number in the array.
– It prints out only the numbers that are divisible by 3: 9, 12, 6, and 18.

Here’s an example program:

// Prompt user for five numbers and store them in an array
var numbers = [];
for (var i = 0; i < 5; i++) {
var userInput = prompt(“Enter a number:”);
numbers.push(parseInt(userInput));
}

// Iterate over the array and print numbers divisible by 3
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] % 3 === 0) {
console.log(numbers[i]);
}
}

Output

2. Create a form that takes an array of numbers to generate inputs and uses a while loop to compute(sum) the product of all the input value numbers in the array.

The task is to create a form that takes an array of numbers as input and uses a while loop to compute the product of all the input values. 
1. Create Form:
You need to create an HTML form that takes an array of numbers as input. Each input field in the form represents a number.
2. Use a While Loop:
You’ll use a while loop to iterate through the form inputs and calculate the product of the entered numbers.
3. Compute Product:
Inside the loop, you’ll multiply each input value to compute the product.
4. Display Result: Finally, you’ll display the result, which is the product of all the entered numbers.

Here’s an example program:

<body>

<h2>Product Calculator</h2>

<form id=”numberForm”>
<label for=”numbers”>Enter Numbers (comma-separated):</label>
<input type=”text” id=”numbers” placeholder=”e.g., 2, 4, 6″>
<button type=”button” onclick=”calculateProduct()”>Calculate Product</button>
</form>

<p id=”result”></p>

<script>
function calculateProduct() {
var inputNumbers = document.getElementById(“numbers”).value.split(‘,’).map(Number);
var product = 1;
var i = 0;

while (i < inputNumbers.length) {
product *= inputNumbers[i];
i++;
}

document.getElementById(“result”).textContent = “Product: ” + product;
}
</script>

</body>

Output

3. Write a program that uses a for loop to iterate over an array of strings and prints out only the strings that contain the letter “e”.

The task is to create a program that uses a for loop to iterate over an array of strings and prints out only the strings that contain the letter “e”.
1. Create an Array:
Define an array of strings that you want to iterate over.
2. Use a For Loop:
Use a for loop to go through each string in the array.
3. Check for the Letter “e”:
Inside the loop, check if each string contains the letter “e”.
4. Print Strings with “e”:
If a string contains “e”, print that string.
Example: [“apple”, “banana”, “orange”, “grape”, “kiwi”, “pear”]

Here’s an example program:

// Example array of strings
var words = [“apple”, “banana”, “orange”, “grape”, “kiwi”, “pear”];

// Use a for loop to iterate over the array
for (var i = 0; i < words.length; i++) {
// Check if the string contains the letter “e”
if (words[i].includes(“e”)) {
// Print the string
console.log(words[i]);
}
}

Output

4. Create a JavaScript function called count Vowels that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string:- IQRA TECHNOLOGY:- 5.

The task is to create a JavaScript function called countVowels that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string.
1. Create a Function:
Define a function named countVowels that takes a string as a parameter.
2. Initialize a Counter:
Inside the function, initialize a counter variable to keep track of the number of vowels.
3. Iterate Over Characters:
Use a loop to iterate over each character in the input string.
4. Check for Vowels:
For each character, check if it is a vowel (a, e, i, o, u).
5. Increment Counter:
If a character is a vowel, increment the counter.
6. Return Result:
After the loop, return the final count of vowels.
Example:
string:- IQRA TECHNOLOGY.

Here’s an example program:

function countVowels(inputString) {
// Initialize counter
var vowelCount = 0;

// Convert the input string to lowercase to handle both uppercase and lowercase vowels
var lowercaseString = inputString.toLowerCase();

// Iterate over each character in the string
for (var i = 0; i < lowercaseString.length; i++) {
// Check if the character is a vowel
if (“aeiou”.includes(lowercaseString[i])) {
// Increment the counter
vowelCount++;
}
}

// Return the final count of vowels
return vowelCount;
}

// Example usage
var inputString = “IQRA TECHNOLOGY”;
var result = countVowels(inputString);

console.log(“Number of vowels in ‘” + inputString + “‘: ” + result);

Output

5. An Armstrong number is a special number. You take a number, do some math with its digits, and check if the result is the same as the original number. If it’s the same, it’s an Armstrong number!

An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or pluperfect number) is a special number where the sum of its digits each raised to the power of the number of digits is equal to the number itself.
1. Take a Number: Choose a number to check if it’s an Armstrong number.
2. Determine the Number of Digits: Count how many digits are there in the number. Let’s say there are n digits.
3. Raise Each Digit to the Power of n: For each digit in the number, raise it to the power of n.
4. Sum the Results: Add all the results obtained from step 3.
5. Check if the Result is Equal to the Original Number: If the sum from step 4 is equal to the original number, then it’s an Armstrong number.
Example with 153:
– Take the number 153.
– It has 3 digits.
– Raise each digit to the power of 3: \(1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153\).
– The sum is equal to the original number (153), so 153 is an Armstrong number.

Here’s an example program:

function isArmstrongNumber(number) {
// Convert the number to a string to determine the number of digits
var numStr = number.toString();
var numDigits = numStr.length;

// Calculate the sum of each digit raised to the power of the number of digits
var sum = 0;
for (var i = 0; i < numDigits; i++) {
sum += Math.pow(parseInt(numStr[i]), numDigits);
}

// Check if the sum is equal to the original number
return sum === number;
}

// Example usage
var exampleNumber = 153;
if (isArmstrongNumber(exampleNumber)) {
console.log(exampleNumber + ” is an Armstrong number!”);
} else {
console.log(exampleNumber + ” is not an Armstrong number.”);
}

Output

6. Create a JavaScript program that generates a FizzBuzz variation for each number from 1 to 100. The rules are as follows:
– If a number is divisible by 3. print “Fizz.”
– If a number is divisible by 5, print “Buzz.”
– If a number is divisible by both 3 and 5, print “FizzBuzz.”
For other numbers, print the number itself.
Your program should display the results from 1 to 100.

– A for loop iterates from 1 to 100.
– The if-else conditions check whether the current number is divisible by 3, 5, both 3 and 5, or neither.
– Depending on the condition, it prints “Fizz,” “Buzz,” “FizzBuzz,” or the number itself.

Here’s an example program:

for (var i = 1; i <= 100; i++) {
// Check if the number is divisible by both 3 and 5
if (i % 3 === 0 && i % 5 === 0) {
console.log(“FizzBuzz”);
}
// Check if the number is divisible by 3
else if (i % 3 === 0) {
console.log(“Fizz”);
}
// Check if the number is divisible by 5
else if (i % 5 === 0) {
console.log(“Buzz”);
}
// For other numbers, print the number itself
else {
console.log(i);
}
}

Output

7. Write a JavaScript program that generates a number pyramid pattern based on user input. If the user enters the number 5, the program should produce the following pattern
1
22
333
4444
55555

This Task is to generate a number pyramid pattern based on user input, you can use nested loops.
1. Use Prompt for the user to enter the number of rows for the pyramid.
2. Take An outer loop (for) that iterates through each row from 1 to the specified number of rows.
3. Inside the outer loop, Take an inner loop (for) that prints the current row number repeatedly based on the row index.
4. After each row is printed, add a line break (<br>) to move to the next line.

Here’s an example program:

// Get user input for the number of rows
var numberOfRows = parseInt(prompt(“Enter the number of rows for the pyramid:”));

// Outer loop for each row
for (var i = 1; i <= numberOfRows; i++) {
// Inner loop for each number in the row
for (var j = 1; j <= i; j++) {
// Print the current row number
document.write(i);
}
// Move to the next line after completing each row
document.write(“<br>”);
}

Output