Assignments Of Day 6: Loops in JavaScript
Assignments on Loops in JavaScript
Below are some assignments based on the loops concept covered in the lecture, along with their solutions.
Assignment 1: Print Even Numbers Between 1 and 50
Problem:
Write a for loop that prints all the even numbers between 1 and 50 (inclusive).
Solution:
javascript
Copy code
for (let i = 1; i <= 50; i++) {
if (i % 2 === 0) {
console.log(i); // Prints all even numbers between 1 and 50
}
}
Assignment 2: Sum of All Numbers from 1 to 100
Problem:
Write a while loop to find the sum of all numbers from 1 to 100.
Solution:
javascript
Copy code
let sum = 0;
let i = 1;
while (i <= 100) {
sum += i; // Add current value of i to sum
i++; // Increment i by 1
}
console.log("Sum of numbers from 1 to 100:", sum); // Outputs the sum
Assignment 3: Print Multiplication Table for a Given Number
Problem:
Write a for loop that takes a number as input and prints the multiplication table for that number up to 10.
Solution:
javascript
Copy code
let number = 5; // You can change this to any number
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
Assignment 4: Print a Triangle of Stars Using Nested Loops
Problem:
Use nested loops to print the following triangle pattern of stars:
markdown
Copy code
*
**
***
****
*****
Solution:
javascript
Copy code
for (let i = 1; i <= 5; i++) {
let stars = ''; // Empty string to hold stars for each line
for (let j = 1; j <= i; j++) {
stars += '*'; // Add one star to the string in each iteration of inner loop
}
console.log(stars); // Print the stars string for each row
}
Assignment 5: Print Fibonacci Series Up to N Terms
Problem:
Write a do...while loop that prints the Fibonacci series up to the n terms, where n is provided as input.
Solution:
javascript
Copy code
let n = 10; // You can change this to any number
let a = 0, b = 1;
let count = 0;
do {
console.log(a);
let nextTerm = a + b; // Calculate the next term
a = b; // Update a to b
b = nextTerm; // Update b to nextTerm
count++; // Increment the count
} while (count < n);
Assignment 6: Reverse a Number Using a Loop
Problem:
Write a while loop that reverses a given number.
Solution:
javascript
Copy code
let number = 12345;
let reversed = 0;
while (number > 0) {
let digit = number % 10; // Get the last digit
reversed = (reversed * 10) + digit; // Append the digit to reversed number
number = Math.floor(number / 10); // Remove the last digit
}
console.log("Reversed Number:", reversed); // Outputs the reversed number
Assignment 7: Count Down from 10 to 1
Problem:
Write a do...while loop that counts down from 10 to 1 and prints the numbers.
Solution:
javascript
Copy code
let i = 10;
do {
console.log(i);
i--;
} while (i >= 1); // Loop will stop when i is less than 1
Assignment 8: Find the Factorial of a Number
Problem:
Write a for loop to calculate the factorial of a given number. Factorial of n is the product of all positive integers less than or equal to n (n!).
Solution:
javascript
Copy code
let number = 5; // You can change this to any number
let factorial = 1;
for (let i = 1; i <= number; i++) {
factorial *= i; // Multiply factorial by i in each iteration
}
console.log("Factorial of", number, "is", factorial); // Outputs the factorial
Assignment 9: Print Odd Numbers Between 1 and 100
Problem:
Write a while loop that prints all odd numbers between 1 and 100.
Solution:
javascript
Copy code
let i = 1;
while (i <= 100) {
console.log(i); // Print odd number
i += 2; // Increment i by 2 to get the next odd number
}
Assignment 10: Print a Diamond Shape Using Stars
Problem:
Write a nested loop to print a diamond shape using stars (*):
markdown
Copy code
*
***
*****
***
*
Solution:
javascript
Copy code
let n = 5; // You can change this to any odd number
// Upper half of the diamond
for (let i = 1; i <= n; i += 2) {
let spaces = ' '.repeat((n - i) / 2); // Spaces to center the stars
let stars = '*'.repeat(i); // Stars for the current row
console.log(spaces + stars + spaces); // Print each row
}
// Lower half of the diamond
for (let i = n - 2; i >= 1; i -= 2) {
let spaces = ' '.repeat((n - i) / 2); // Spaces to center the stars
let stars = '*'.repeat(i); // Stars for the current row
console.log(spaces + stars + spaces); // Print each row
}
Assignment 11: Find the Largest of Three Numbers Using a Loop
Problem:
Write a for loop that takes three numbers as input and prints the largest number.
Solution:
javascript
Copy code
let numbers = [12, 45, 23]; // Example numbers
let largest = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update largest if the current number is bigger
}
}
console.log("Largest number is:", largest); // Outputs the largest number
Assignment 12: Print a Square Pattern of Stars
Problem:
Write a for loop to print the following square pattern of stars (*):
markdown
Copy code
*****
*****
*****
*****
*****
Solution:
javascript
Copy code
let size = 5; // You can change this to any number
for (let i = 1; i <= size; i++) {
let stars = '';
for (let j = 1; j <= size; j++) {
stars += '*'; // Add one star for each column in a row
}
console.log(stars); // Print the row of stars
}
These assignments cover the basic use of loops and help students practice using loops effectively for different types of problems.
4o mini
You said:
give more
ChatGPT said:
ChatGPT
Here are more assignments related to loops in JavaScript, along with their solutions:
Assignment 13: Print Numbers Divisible by 3 and 5
Problem:
Write a for loop that prints all numbers between 1 and 100 that are divisible by both 3 and 5.
Solution:
javascript
Copy code
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log(i); // Print numbers divisible by both 3 and 5
}
}
Assignment 14: Count the Number of Vowels in a String
Problem:
Write a for loop that counts the number of vowels (a, e, i, o, u) in a given string.
Solution:
javascript
Copy code
let str = "Hello World";
let vowelCount = 0;
let vowels = "aeiou";
for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i].toLowerCase())) {
vowelCount++; // Increment if a vowel is found
}
}
console.log("Number of vowels:", vowelCount); // Outputs the count of vowels
Assignment 15: Print Palindrome Numbers Between 1 and 1000
Problem:
Write a for loop that prints all palindrome numbers between 1 and 1000. A palindrome number is one that reads the same backward as forward (e.g., 121, 333).
Solution:
javascript
Copy code
for (let i = 1; i <= 1000; i++) {
let num = i.toString();
let reversedNum = num.split('').reverse().join('');
if (num === reversedNum) {
console.log(i); // Print palindrome numbers
}
}
Assignment 16: Sum of All Odd Numbers Between 1 and 100
Problem:
Write a for loop that calculates the sum of all odd numbers between 1 and 100.
Solution:
javascript
Copy code
let sum = 0;
for (let i = 1; i <= 100; i += 2) {
sum += i; // Add each odd number to sum
}
console.log("Sum of odd numbers between 1 and 100:", sum); // Outputs the sum
Assignment 17: Print a Pyramid Pattern
Problem:
Write a for loop to print the following pyramid pattern using stars (*):
markdown
Copy code
*
***
*****
*******
*********
Solution:
javascript
Copy code
let n = 5; // The number of rows in the pyramid
for (let i = 1; i <= n; i++) {
let spaces = ' '.repeat(n - i); // Add spaces before stars
let stars = '*'.repeat(2 * i - 1); // Stars increase with each row
console.log(spaces + stars + spaces); // Print the pyramid row
}
Assignment 18: Find the Prime Numbers Between 1 and 100
Problem:
Write a for loop that prints all prime numbers between 1 and 100. A prime number is a number greater than 1 that is divisible only by 1 and itself.
Solution:
javascript
Copy code
for (let i = 2; i <= 100; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break; // No need to check further if it's divisible
}
}
if (isPrime) {
console.log(i); // Print prime numbers
}
}
Assignment 19: Reverse a String Using a Loop
Problem:
Write a for loop that reverses a given string.
Solution:
javascript
Copy code
let str = "JavaScript";
let reversedStr = "";
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i]; // Append characters in reverse order
}
console.log("Reversed String:", reversedStr); // Outputs the reversed string
Assignment 20: Count the Occurrences of a Specific Character in a String
Problem:
Write a for loop to count how many times a specific character (e.g., 'a') appears in a given string.
Solution:
javascript
Copy code
let str = "JavaScript is awesome";
let count = 0;
let charToCount = 'a';
for (let i = 0; i < str.length; i++) {
if (str[i].toLowerCase() === charToCount) {
count++; // Increment count if character matches
}
}
console.log(`Character '${charToCount}' appears ${count} times.`); // Outputs the count
Assignment 21: Print a Rectangle Pattern Using Stars
Problem:
Write a for loop to print the following rectangle pattern using stars (*):
markdown
Copy code
*******
*******
*******
Solution:
javascript
Copy code
let rows = 3;
let cols = 7;
for (let i = 0; i < rows; i++) {
let stars = '';
for (let j = 0; j < cols; j++) {
stars += '*'; // Add stars for each column
}
console.log(stars); // Print each row of stars
}
Assignment 22: Print Fibonacci Sequence Using Loops
Problem:
Write a for loop that prints the first 10 terms of the Fibonacci sequence.
Solution:
javascript
Copy code
let n = 10;
let a = 0, b = 1;
for (let i = 0; i < n; i++) {
console.log(a); // Print the current Fibonacci number
let nextTerm = a + b;
a = b; // Update a to b
b = nextTerm; // Update b to nextTerm
}
Assignment 23: Find the Factorial of a Number Using While Loop
Problem:
Write a while loop that calculates the factorial of a given number.
Solution:
javascript
Copy code
let num = 6; // You can change this to any number
let factorial = 1;
let i = 1;
while (i <= num) {
factorial *= i; // Multiply factorial by i in each iteration
i++;
}
console.log(`Factorial of ${num} is ${factorial}`); // Outputs the factorial
Assignment 24: Print a Right-Angle Triangle Pattern
Problem:
Write a for loop to print the following right-angle triangle pattern using stars (*):
markdown
Copy code
*
**
***
****
*****
Solution:
javascript
Copy code
let rows = 5;
for (let i = 1; i <= rows; i++) {
let stars = '';
for (let j = 1; j <= i; j++) {
stars += '*'; // Add stars for the current row
}
console.log(stars); // Print each row
}
Assignment 25: Sum of Digits of a Number
Problem:
Write a while loop that calculates the sum of the digits of a given number.
Solution:
javascript
Copy code
let num = 12345;
let sum = 0;
while (num > 0) {
sum += num % 10; // Add the last digit to the sum
num = Math.floor(num / 10); // Remove the last digit
}
console.log("Sum of digits:", sum); // Outputs the sum of digits
