Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Week_13_Intangible_Technologies_Assessment_Intro_to_JavaScript(Alojipan) (1)

The document outlines a laboratory exercise for JavaScript problem solving, including objectives and prerequisites. It contains several coding tasks such as reversing a number, sorting strings alphabetically, counting vowels, capitalizing first letters of words, and calculating dates and basic arithmetic operations. Each task is accompanied by sample data, expected outputs, and corresponding HTML and JavaScript code snippets.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Week_13_Intangible_Technologies_Assessment_Intro_to_JavaScript(Alojipan) (1)

The document outlines a laboratory exercise for JavaScript problem solving, including objectives and prerequisites. It contains several coding tasks such as reversing a number, sorting strings alphabetically, counting vowels, capitalizing first letters of words, and calculating dates and basic arithmetic operations. Each task is accompanied by sample data, expected outputs, and corresponding HTML and JavaScript code snippets.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

UEL131

(INTANGIBLE TECHNOLOGIES)

EXERCISE

13
PROBLEM SOLVING USING JAVASCRIPT

Student Name / Group Shiel Dawn Amon Alojipan


Name:

Name Role
Members (if Group):

Section: BSIT 3-1


Professor: Alex Hernandez
I. LABORATORY ACTIVITY
Objectives:

● Understand and apply core JavaScript concepts: Students will be able to define and use key

JavaScript concepts such as variables, data types, functions, loops, conditionals, and objects to
write simple programs and manipulate data effectively.

Prerequisites:

● Knowledge of JavaScript

● Notepad++ or VSCode

Part 1. Problem Solving using JavaScript


a. Reverse A Number
Write a JavaScript function that reverse a number.
Sample Data and output:
Example x = 32243;
Expected Output : 34223

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reverse a Number</title>
</head>
<body>

<script>
function reverseNumber(x) {
// Convert the number to a string, reverse it, and convert it back to a number
var reversed = x.toString().split('').reverse().join('');
return parseInt(reversed);
}

// Test Data
var x = 32243;
document.write("Reversed number: " + reverseNumber(x));
</script>

</body>
</html>

Passed Strings with Letters in Alphabetical Order


Write a JavaScript function that returns a passed string with letters in alphabetical order.
Example string : 'webmaster'
Expected Output : 'abeemrstw'
Note: Assume punctuation and numbers symbols are not included in the passed
string..

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sort Letters Alphabetically</title>
</head>
<body>

<script>
function sortStringAlphabetically(str) {
// Convert string to an array of characters, sort the array, and join it back into a string
return str.split('').sort().join('');
}

// Test Data
var inputString = 'webmaster';
document.write("Sorted string: " + sortStringAlphabetically(inputString));
</script>
</body>
</html>

Number of Vowels
Write a JavaScript function that accepts a string as a parameter and counts the
number of vowels within the string.
Note : As the letter 'y' can be regarded as both a vowel and a consonant, we do
not count 'y' as vowel here.
Sample Data and output:
Example string : 'The quick brown fox'
Expected Output : 5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Count Vowels</title>
</head>
<body>

<script>
function countVowels(str) {
// Define vowels
const vowels = 'aeiouAEIOU';
let count = 0;

// Loop through the string and check for vowels


for (let i = 0; i < str.length; i++) {
if (vowels.includes(str[i])) {
count++;
}
}

return count;
}

// Test Data
var inputString = 'The quick brown fox';
document.write("Number of vowels: " + countVowels(inputString));
</script>

</body>
</html>

Write a JavaScript function that accepts a string as a parameter and converts the first letter of
each word of the string in upper case.
Example string : 'the quick brown fox'
Expected Output : 'The Quick Brown Fox '

Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Capitalize First Letter</title>
</head>
<body>

<script>
function capitalizeFirstLetter(str) {
// Split the string into words
const words = str.split(' ');

// Loop through each word and capitalize the first letter


for (let i = 0; i < words.length; i++) {
if (words[i].length > 0) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
}
}

// Join the words back into a string and return


return words.join(' ');
}

// Test Data
var inputString = 'the quick brown fox';
document.write("Converted string: " + capitalizeFirstLetter(inputString));
</script>

</body>
</html>

Write a JavaScript program to get the current date.


Expected Output :
mm-dd-yyyy, mm/dd/yyyy or dd-mm-yyyy, dd/mm/yyyy

Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Current Date</title>
</head>
<body>

<script>
function getCurrentDate() {
// Get the current date
let currentDate = new Date();
// Get the individual components of the date
let day = currentDate.getDate();
let month = currentDate.getMonth() + 1; // Months are 0-indexed
let year = currentDate.getFullYear();

// Add leading zeros to day and month if needed


day = (day < 10) ? '0' + day : day;
month = (month < 10) ? '0' + month : month;

// Format the date in different styles


let format1 = month + '-' + day + '-' + year; // mm-dd-yyyy
let format2 = month + '/' + day + '/' + year; // mm/dd/yyyy
let format3 = day + '-' + month + '-' + year; // dd-mm-yyyy
let format4 = day + '/' + month + '/' + year; // dd/mm/yyyy

// Display the result


document.write("Format 1: " + format1 + "<br>");
document.write("Format 2: " + format2 + "<br>");
document.write("Format 3: " + format3 + "<br>");
document.write("Format 4: " + format4 + "<br>");
}

// Call the function to display the date


getCurrentDate();
</script>

</body>
</html>
Write a JavaScript program to calculate number of days left until next Christmas.

Write a JavaScript program to calculate multiplication and division of two numbers (input from
user).
Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator & Date Functions</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}

.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
width: 300px;
}

.result, .calc-result, .christmas-result, .sign-result {


margin-top: 20px;
font-size: 18px;
font-weight: bold;
}

input {
margin: 5px 0;
padding: 5px;
width: 80%;
}

button {
margin: 5px;
padding: 8px 12px;
}
</style>
</head>
<body>
<div class="container">
<h2>Get Current Date</h2>
<button onclick="getCurrentDate()">Show Current Date</button>
<div class="result" id="result"></div>

<h2>Days Until Christmas</h2>


<button onclick="daysUntilChristmas()">Show Days Until Christmas</button>
<div class="christmas-result" id="christmas-result"></div>

<h2>Calculator</h2>
<div>
<input type="number" id="num1" placeholder="1st Number">
<input type="number" id="num2" placeholder="2nd Number">
</div>
<button onclick="calculate('multiply')">Multiply</button>
<button onclick="calculate('divide')">Divide</button>
<div class="calc-result" id="calc-result"></div>

<h2>Find Sign of Product</h2>


<div>
<input type="number" id="signNum1" placeholder="1st Number">
<input type="number" id="signNum2" placeholder="2nd Number">
<input type="number" id="signNum3" placeholder="3rd Number">
</div>
<button onclick="findSign()">Find Sign</button>
<div class="sign-result" id="sign-result"></div>
</div>

<script>
function getCurrentDate() {
let currentDate = new Date();
let day = currentDate.getDate();
let month = currentDate.getMonth() + 1;
let year = currentDate.getFullYear();

day = (day < 10) ? '0' + day : day;


month = (month < 10) ? '0' + month : month;

let format1 = month + '-' + day + '-' + year;


let format2 = month + '/' + day + '/' + year;
let format3 = day + '-' + month + '-' + year;
let format4 = day + '/' + month + '/' + year;

document.getElementById("result").innerHTML =
'Format 1: ' + format1 + '<br>' +
'Format 2: ' + format2 + '<br>' +
'Format 3: ' + format3 + '<br>' +
'Format 4: ' + format4;
}

function daysUntilChristmas() {
let today = new Date();
let currentYear = today.getFullYear();
let nextChristmas = new Date(currentYear, 11, 25);

if (today > nextChristmas) {


nextChristmas.setFullYear(currentYear + 1);
}

let oneDay = 1000 * 60 * 60 * 24;


let daysLeft = Math.ceil((nextChristmas - today) / oneDay);
document.getElementById("christmas-result").innerHTML =
daysLeft + " days left until Christmas!";
}

function calculate(operation) {
let num1 = parseFloat(document.getElementById("num1").value);
let num2 = parseFloat(document.getElementById("num2").value);
let result = 0;

if (isNaN(num1) || isNaN(num2)) {
document.getElementById("calc-result").innerHTML = "Please enter valid numbers.";
return;
}

if (operation === 'multiply') {


result = num1 * num2;
} else if (operation === 'divide') {
if (num2 === 0) {
document.getElementById("calc-result").innerHTML = "Division by zero is not allowed.";
return;
}
result = num1 / num2;
}

document.getElementById("calc-result").innerHTML = "The Result Is: " + result;


}

function findSign() {
let num1 = parseFloat(document.getElementById("signNum1").value);
let num2 = parseFloat(document.getElementById("signNum2").value);
let num3 = parseFloat(document.getElementById("signNum3").value);
if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {
alert("Please enter all three numbers.");
return;
}

let product = num1 * num2 * num3;


let sign = (product > 0) ? "+" : "-";

document.getElementById("sign-result").innerHTML = "The sign is: " + sign;


alert("The sign of the product is: " + sign);
}
</script>

</body>
</html>

Conditional Statement and Loops


Write a JavaScript conditional statement to find the sign of product of three numbers. Display an
alert box with the specified sign.
Sample numbers : 3, -7, 2
Output : The sign is –

Output
function findSign() {
let num1 = parseFloat(document.getElementById("signNum1").value);
let num2 = parseFloat(document.getElementById("signNum2").value);
let num3 = parseFloat(document.getElementById("signNum3").value);

if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {


alert("Please enter all three numbers.");
return;
}

let product = num1 * num2 * num3;


let sign = (product > 0) ? "+" : "-";

document.getElementById("sign-result").innerHTML = "The sign is: " + sign;


alert("The sign of the product is: " + sign);
}
</script>

Write a simple JavaScript program to join all elements of the following array into a string.
Expected Output :
"Red,Green,White,Black"
"Red,Green,White,Black"
"Red+Green+White+Black"

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Join Array Elements</title>
</head>
<body>

<script>
// Define the array
var colors = ["Red", "Green", "White", "Black"];

// Join elements using commas


var commaSeparated = colors.join(",");

// Join elements using plus signs


var plusSeparated = colors.join("+");

// Display the results


document.write('Comma Separated: ' + commaSeparated + "<br>");
document.write('Comma Separated: ' + commaSeparated + "<br>");
document.write('Plus Separated: ' + plusSeparated + "<br>");
</script>

</body>
</html>

Write a JavaScript program to sort the items of an array.


Sample array : var arr1 = [ 3, 8, 7, 6, 5, -4, 3, 2, 1 ];
Sample Output : -4,-3,1,2,3,5,6,7,8
Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sort Array Items</title>
</head>
<body>

<script>
// Define the array
var arr1 = [3, 8, 7, 6, 5, -4, 3, 2, 1];

// Sort the array in ascending order


arr1.sort(function(a, b) {
return a - b;
});

// Display the sorted array as comma-separated values


document.write('Sorted Array: ' + arr1.join(",") + "<br>");
</script>

</body>
</html>

Write a JavaScript program to display the colors in the following way :


Here is the sample array:
color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];
o = ["th","st","nd","rd"]
Output
"1st choice is Blue ."
"2nd choice is Green."
"3rd choice is Red."

Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Choices</title>
</head>
<body>

<script>
// Define the color array
var color = ["Blue ", "Green", "Red", "Orange", "Violet", "Indigo", "Yellow "];

// Define the suffix array


var suffix = ["th", "st", "nd", "rd"];

// Loop through the color array


for (var i = 0; i < color.length; i++) {
// Determine the suffix based on the position
var suffixIndex = (i + 1) % 10;
var suffixToUse = suffix[0]; // Default "th"
if (suffixIndex === 1) {
suffixToUse = suffix[1]; // "st"
} else if (suffixIndex === 2) {
suffixToUse = suffix[2]; // "nd"
} else if (suffixIndex === 3) {
suffixToUse = suffix[3]; // "rd"
}

// Display the result


document.write((i + 1) + suffixToUse + " choice is " + color[i] + ".<br>");
}
</script>

</body>
</html>

Write a JavaScript for loop that will iterate from 0 to 15. For each iteration, it will check if the
current number is odd or even, and display a message to the screen.
Sample Output :
"0 is even"
"1 is odd"
"2 is even"

Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Odd or Even</title>
</head>
<body>

<script>
// Iterate from 0 to 2
for (var i = 0; i <= 2; i++) {
if (i % 2 === 0) {
// If the number is even
document.write(i + " is even<br>");
} else {
// If the number is odd
document.write(i + " is odd<br>");
}
}
</script>

</body>
</html>

Write a JavaScript conditional statement to find the largest of five numbers. Display an alert box
to show the result.
Sample numbers : -5, -2, -6, 0, -1
Output : 0

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Largest of Five Numbers</title>
</head>
<body>

<script>
// Define the five numbers
var num1 = -5, num2 = -2, num3 = -6, num4 = 0, num5 = -1;

// Use a conditional statement to find the largest number


var largest = num1;

if (num2 > largest) {


largest = num2;
}
if (num3 > largest) {
largest = num3;
}
if (num4 > largest) {
largest = num4;
}
if (num5 > largest) {
largest = num5;
}

// Display the largest number using an alert box


alert(largest);
</script>
</body>
</html>

Write a JavaScript conditional statement to sort three numbers. Display an alert box to show the
result.
Sample numbers : 3, -7, 2
Output : The sign is –

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sort and Check Sign of Three Numbers</title>
</head>
<body>
<script>
// Prompt the user for three numbers
var num1 = parseInt(prompt("Enter the first number:"));
var num2 = parseInt(prompt("Enter the second number:"));
var num3 = parseInt(prompt("Enter the third number:"));

// Sort the numbers in ascending order


var numbers = [num1, num2, num3];
numbers.sort(function(a, b) {
return a - b;
});

// Check the sign of the product of the numbers


var product = num1 * num2 * num3;
var sign = (product < 0) ? "negative" : "positive"; // If product is negative, the sign is negative

// Display the sorted numbers and the sign of their product in an alert box
alert("Sorted numbers: " + numbers.join(", ") + "\nThe sign is: " + sign);
</script>

</body>
</html>

Write a JavaScript function to get the last day of a month.


Test Data :
document.write(lastday(2014,0));
document.write(lastday(2014,1));
document.write(lastday(2014,11));
Output :
31
28
31

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Last Day of the Month</title>
</head>
<body>

<script>
// Function to get the last day of a month
function lastday(year, month) {
// Create a new date object for the first day of the next month
var date = new Date(year, month + 1, 0); // 0 day means the last day of the previous month
return date.getDate(); // Returns the last day of the month
}
// Test the function with the provided test data
document.write(lastday(2014, 0) + "<br>"); // January (0)
document.write(lastday(2014, 1) + "<br>"); // February (1)
document.write(lastday(2014, 11) + "<br>"); // December (11)
</script>

</body>
</html>

Write a JavaScript program to calculate age.


Test Data :
document.write(calculate_age(new Date(1982, 11, 4)));
32
document.write(calculate_age(new Date(1962, 1, 1)));
53

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculate Age</title>
</head>
<body>

<script>
// Function to calculate age based on date of birth
function calculate_age(dob) {
var today = new Date();
var age = today.getFullYear() - dob.getFullYear();
var m = today.getMonth() - dob.getMonth();

// Adjust age if the birthday hasn't occurred yet this year


if (m < 0 || (m === 0 && today.getDate() < dob.getDate())) {
age--;
}

return age;
}

// Test the function with the provided test data


document.write(calculate_age(new Date(1982, 11, 4)) + "<br>"); // Birthdate: December 4, 1982
document.write(calculate_age(new Date(1962, 1, 1)) + "<br>"); // Birthdate: January 1, 1962
</script>

</body>
</html>
Write a JavaScript function to get the week end date

Output

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Weekend Date</title>
</head>
<body>

<script>
function getWeekendDate(date) {
// Get the day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
var dayOfWeek = date.getDay();

// Calculate the days to add to get to the next Saturday (6) or Sunday (0)
var daysToSaturday = 6 - dayOfWeek; // days to next Saturday
var daysToSunday = (dayOfWeek === 0) ? 0 : 7 - dayOfWeek; // days to next Sunday
// Get the next Saturday or Sunday
var saturday = new Date(date);
saturday.setDate(date.getDate() + daysToSaturday);

var sunday = new Date(date);


sunday.setDate(date.getDate() + daysToSunday);

// Format the output as MM-DD-YYYY


var formatDate = (d) => {
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
return `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}-${year}`;
};

// Display both Saturday and Sunday dates


return `Next Saturday: ${formatDate(saturday)}<br>Next Sunday: ${formatDate(sunday)}`;
}

// Test Data
var date = new Date(); // Current date
document.write(getWeekendDate(date));
</script>

</body>
Part 2. Question and Answer
Evaluate each of the following Javascript expressions and show the value.
Problem Value

Trace the following code by showing the values of the 3 variables in the table on the right, for each line of
code that is executed (after the line is executed):
Code X Y Z

You might also like