CST463 · S7 CSE
JavaScript programs
Programming exercises with complete, runnable HTML solutions for each.
Source: js_qa.docx — course material by Kiran V.K., published here so it is readable without a Google account.
- Write a JavaScript program that takes two numbers as variables and prints out their sum, difference, product, and quotient to the console
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rectangle Area Calculator</title>
</head>
<body>
<h1>Rectangle Area Calculator</h1>
<p>This script calculates the area of a rectangle with sides 7 and 8 when the page loads.</p>
<script>
// Hardcoded values for the sides
var length = 7;
var width = 8;
// Calculate the area
var area = length * width;
// Log the area to the console
console.log("The area of the rectangle is: " + area);
alert("The area of the rectangle is: " + area);
</script>
</body>
</html>- Create a script that calculates and logs the area of a rectangle with the sides of 7 and 8.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rectangle Area Calculator</title>
</head>
<body>
<h1>Rectangle Area Calculator</h1>
<p>This script calculates the area of a rectangle with sides 7 and 8 when the page loads.</p>
<script>
// Hardcoded values for the sides
var length = 7;
var width = 8;
// Calculate the area
var area = length * width;
// Log the area to the console
console.log("The area of the rectangle is: " + area);
alert("The area of the rectangle is: " + area);
</script>
</body>
</html>- Ask the user to enter two numbers using prompt(), and then output the modulus (remainder of the division) of those two numbers
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modulus Calculator</title>
</head>
<body>
<h1>Modulus Calculator</h1>
<p>This script prompts the user to enter two numbers and calculates the remainder when the first number is divided by the second number.</p>
<script>
// Prompt the user to enter the first number
var num1 = prompt("Enter the first number:");
// Prompt the user to enter the second number
var num2 = prompt("Enter the second number:");
// Convert the input strings to numbers
num1 = Number(num1);
num2 = Number(num2);
// Calculate the modulus (remainder)
var remainder = num1 % num2;
// Output the result
alert("The remainder of " + num1 + " divided by " + num2 + " is: " + remainder);
console.log("The remainder of " + num1 + " divided by " + num2 + " is: " + remainder);
</script>
</body>
</html>- Write a JavaScript function that takes a number as an argument and logs whether the number is even or odd.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Even or Odd Checker</title>
</head>
<body>
<h1>Even or Odd Checker</h1>
<p>This script asks the user to enter a number and tells whether it is even or odd.</p>
<script>
// Prompt the user to enter a number
var number = prompt("Enter a number:");
// Convert the input string to a number
number = Number(number);
// Check if the number is even or odd
if (number % 2 === 0) {
alert(number + " is even.");
console.log(number + " is even.");
} else {
alert(number + " is odd.");
console.log(number + " is odd.");
}
</script>
</body>
</html>- Create a script that asks the user for a score out of 100 using
prompt(), then logs "Pass" if the score is above 50 and "Fail" if the score is 50 or below.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pass or Fail Checker</title>
</head>
<body>
<h1>Pass or Fail Checker</h1>
<p>This script asks the user for a score out of 100 and tells whether the score is a "Pass" or "Fail".</p>
<script>
// Ask the user for a score out of 100 using prompt
var score = prompt("Enter your score (out of 100):");
// Convert the input to a number
score = Number(score);
// Check if the score is above 50 or not and log the result
if (score > 50) {
alert("Pass");
console.log("Pass");
} else {
alert("Fail");
console.log("Fail");
}
</script>
</body>
</html>- Make a decision-making script that logs different greetings depending on the time of day (morning, afternoon, evening) that the user inputs.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Time-Based Greeting</title>
</head>
<body>
<h1>Time-Based Greeting</h1>
<p>This script asks the user to input the time of day and gives a greeting depending on whether it's morning, afternoon, or evening.</p>
<script>
// Ask the user to input the time of day (in hours)
var time = prompt("Please enter the time (0-23):");
// Convert the input to a number
time = Number(time);
// Check the time range and log the appropriate greeting
if (time >= 0 && time < 12) {
alert("Good Morning!");
console.log("Good Morning!");
} else if (time >= 12 && time < 17) {
alert("Good Afternoon!");
console.log("Good Afternoon!");
} else if (time >= 17 && time <= 23) {
alert("Good Evening!");
console.log("Good Evening!");
} else {
alert("Invalid input. Please enter a time between 0 and 23.");
console.log("Invalid input. Please enter a time between 0 and 23.");
}
</script>
</body>
</html>- Write a JavaScript loop that counts from 1 to 10 and logs each number to the console.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Count from 1 to 10</title>
</head>
<body>
<h1>Counting from 1 to 10</h1>
<p>This script logs numbers from 1 to 10 to the console using a loop.</p>
<script>
// Loop that counts from 1 to 10
for (var i = 1; i <= 10; i++) {
console.log(i); // Log each number to the console
}
</script>
</body>
</html>- Create a script that lists the multiples of 5 up to 50 (5, 10, 15, ..., 50) using a
forloop.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiples of 5</title>
</head>
<body>
<h1>Multiples of 5 up to 50</h1>
<p>This script logs the multiples of 5 up to 50 (i.e., 5, 10, 15, ..., 50) using a loop.</p>
<script>
// Loop that lists multiples of 5 up to 50
for (var i = 5; i <= 50; i += 5) {
console.log(i); // Log each multiple of 5 to the console
}
</script>
</body>
</html>- Use a
whileloop to simulate a simple guessing game where the user has to guess a predefined number between 1 and 10.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1>
<p>This script generates a random number between 1 and 10, and the user has to guess it.</p>
<script>
// Generate a random number between 1 and 10
var correctNumber = Math.floor(Math.random() * 10) + 1;
// Variable to store the user's guess
var guess = 0;
// While loop to keep asking the user until they guess correctly
while (guess != correctNumber) {
// Ask the user to guess the number
guess = prompt("Guess a number between 1 and 10:");
// Convert the input to a number
guess = Number(guess);
// Check if the guess is correct
if (guess == correctNumber) {
alert("Congratulations! You guessed the correct number.");
console.log("User guessed the correct number: " + guess);
} else {
alert("Wrong guess! Try again.");
console.log("User guessed: " + guess + " (Wrong guess)");
}
}
</script>
</body>
</html>- Define a function that takes a string as an argument and logs that string reversed.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reverse String Function</title>
</head>
<body>
<h1>String Reversal</h1>
<p>This script defines a function that takes a string and logs the reversed string.</p>
<script>
// Function that takes a string as an argument and logs the reversed string
function reverseString(str) {
// Split the string into an array of characters, reverse the array, and join it back into a string
var reversed = str.split('').reverse().join('');
console.log("Original String: " + str);
console.log("Reversed String: " + reversed);
}
// Example usage
reverseString("Hello, World!"); // Logs the reversed string
</script>
</body>
</html>- Write a function that takes an array of numbers as a parameter and returns the sum of the elements.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum of Array Elements</title>
</head>
<body>
<h1>Array Sum Function</h1>
<p>This script defines a function that takes an array of numbers and returns the sum of its elements.</p>
<script>
// Function that takes an array of numbers and returns the sum of its elements
function sumArray(arr) {
var sum = 0;
// Loop through the array and add each element to the sum
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
// Example usage
var numbers = [1, 2, 3, 4, 5];
var result = sumArray(numbers); // Returns the sum of the elements in the array
console.log("The sum of the array elements is: " + result);
</script>
</body>
</html>- Create a function that checks if a number passed to it is a prime number and logs the result.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prime Number Checker</title>
</head>
<body>
<h1>Prime Number Checker</h1>
<p>This script defines a function that checks if a number is prime and logs the result.</p>
<script>
// Function to check if a number is prime
function isPrime(num) {
if (num <= 1) {
console.log(num + " is not a prime number.");
return false;
}
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
console.log(num + " is not a prime number.");
return false;
}
}
console.log(num + " is a prime number.");
return true;
}
// Example usage
isPrime(11); // Logs: 11 is a prime number.
isPrime(4); // Logs: 4 is not a prime number.
</script>
</body>
</html>- Create an array of your favorite fruits and write a JavaScript loop that logs each fruit to the console.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Favorite Fruits</title>
</head>
<body>
<h1>Favorite Fruits</h1>
<p>This script creates an array of favorite fruits and logs each fruit to the console using a loop.</p>
<script>
// Create an array of favorite fruits
var fruits = ["Apple", "Banana", "Mango", "Strawberry", "Grapes"];
// Loop through the array and log each fruit to the console
for (var i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
</script>
</body>
</html>- Write a script that creates an array of numbers, then loops over that array and logs only the even numbers.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Even Numbers in Random Array</title>
</head>
<body>
<h1>Even Numbers in Random Array</h1>
<p>This script creates an array of random numbers and logs only the even numbers.</p>
<script>
// Function to generate a random number between min and max (inclusive)
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Prompt the user to enter the number of elements for the array
var numElements = prompt("Enter the number of elements to generate in the array:");
// Convert the input to a number
numElements = Number(numElements);
// Create an array and populate it with random numbers between 1 and 100
var numbers = [];
for (var i = 0; i < numElements; i++) {
numbers.push(getRandomNumber(1, 100));
}
// Log the generated array
console.log("Generated array:", numbers);
// Loop through the array and log only the even numbers
console.log("Even numbers in the array:");
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
console.log(numbers[i]);
}
}
</script>
</body>
</html>- Ask the user for 5 numbers using
prompt()(one after the other), store them in an array, and then log the array to the console.
javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array of User Numbers</title>
</head>
<body>
<h1>User Input Array</h1>
<p>This script asks the user for 5 numbers and logs them in an array.</p>
<script>
// Create an empty array to store the user's numbers
var numbers = [];
// Loop to ask the user for 5 numbers
for (var i = 0; i < 5; i++) {
var userInput = prompt("Enter a number (" + (i + 1) + "/5):");
// Convert the input to a number and push it to the array
numbers.push(Number(userInput));
}
// Log the array to the console
console.log("The array of numbers you entered is:", numbers);
</script>
</body>
</html>