Web Technologies Assignment
Web Technologies Assignment
1
Manish raj(2301560122)
functionisPalindrome(num) {
let reverse = 0;
let temp = num;
while (temp > 0) {
const remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp = Math.floor(temp / 10);
}
return reverse === num;
}
constnum = 121;
if (isPalindrome(num)) {
console.log("Given number is a palindrome.");
} else {
console.log("Given number is not a palindrome.");
}
Output –
2
Manish raj(2301560122)
functioncalculateRectangleArea(length, width) {
return length * width;
}
functioncalculateCircleArea(radius) {
return Math.PI * radius * radius;
}
functioncalculateSquareArea(side) {
return side * side;
}
functioncalculateTriangleArea(base, height) {
return 0.5 * base * height;
}
let length = 5;
let width = 3;
let radius = 4;
let side = 6;
let base = 8;
let height = 5;
console.log("Area of Rectangle:", calculateRectangleArea(length, width));
console.log("Area of Circle:", calculateCircleArea(radius));
console.log("Area of Square:", calculateSquareArea(side));
console.log("Area of Triangle:", calculateTriangleArea(base, height));
Output –
3
Manish raj(2301560122)
EXPERIMENT 3. JavaScript Program to Swap Two Variables. (with and without using
third variable)
functionswapWithoutTemp(a, b) {
a = a + b;
b = a - b;
a = a - b;
return [a, b];
}
functionswapWithTemp(a, b) {
let temp = a;
a = b;
b = temp;
return [a, b];
}
let x = 10;
let y = 20;
[x, y] = swapWithoutTemp(x, y);
console.log("\nswapping without using third variable:");
console.log("x =", x);
console.log("y =", y);
// Reset values
x = 5;
y = 10;
[x, y] = swapWithTemp(x, y);
console.log("\nAfter swapping using third variable:");
console.log("x =", x);
console.log("y =", y);
Output –
4
Manish raj(2301560122)
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
constcelsius = 30;
constfahrenheit = celsiusToFahrenheit(celsius);
console.log(`${celsius} degrees Celsius is equal to ${fahrenheit} degrees Fahrenheit.`);
Output –
5
Manish raj(2301560122)
function sumDigits(number) {
let sum = 0;
while (number > 0) {
sum += number % 10;
number = Math.floor(number / 10);
}
return sum;
}
const number = 1225;
const result = sumDigits(number);
console.log(`The sum of the digits of ${number} is ${result}.`);
Output –
6
Manish raj(2301560122)
function checkEvenOrOdd(number) {
if (number % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}
const number = 7;
const result = checkEvenOrOdd(number);
console.log(`${number} is ${result}.`);
Output –
7
Manish raj(2301560122)
function findSumOfNumbers(numbers) {
let sum = 0;
for (let i = 0; i<numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
Output –
8
Manish raj(2301560122)
char = char.toLowerCase();
if (char >= 'a' && char <= 'z') {
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
return "Vowel";
} else {
return "Consonant";
}
} else {
return "Not a letter";
}
}
Output –
9
Manish raj(2301560122)
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b !== 0) {
return a / b;
} else {
return "Cannot divide by zero";
}
}
const num1 = 10;
const num2 = 5;
console.log(`Sum: ${add(num1, num2)}`);
console.log(`Difference: ${subtract(num1, num2)}`);
console.log(`Product: ${multiply(num1, num2)}`);
console.log(`Quotient: ${divide(num1, num2)}`);
Output –
10
Manish raj(2301560122)
EXPERIMENT 10. JavaScript Program to Find the Largest Among Three Numbers
(using if-else loop)
11
Manish raj(2301560122)
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Simple Calculator</title>
<style>
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
}
</style>
</head>
<body>
<h2>Simple Calculator</h2>
<input type="text" id="display" disabled /><br /><br />
<input type="button" value="1" onclick="appendToDisplay('1')" />
<input type="button" value="2" onclick="appendToDisplay('2')" />
<input type="button" value="3" onclick="appendToDisplay('3')" />
<input type="button" value="+" onclick="appendToDisplay('+')" /><br /><br />
<input type="button" value="4" onclick="appendToDisplay('4')" />
<input type="button" value="5" onclick="appendToDisplay('5')" />
<input type="button" value="6" onclick="appendToDisplay('6')" />
<input type="button" value="-" onclick="appendToDisplay('-')" /><br /><br />
<input type="button" value="7" onclick="appendToDisplay('7')" />
<input type="button" value="8" onclick="appendToDisplay('8')" />
<input type="button" value="9" onclick="appendToDisplay('9')" />
<input type="button" value="*" onclick="appendToDisplay('*')" /><br /><br />
<input type="button" value="C" onclick="clearDisplay()" />
<input type="button" value="0" onclick="appendToDisplay('0')" />
<input type="button" value="=" onclick="calculate()" />
<input type="button" value="/" onclick="appendToDisplay('/')" /><br /><br />
<script>
function appendToDisplay(value) {
document.getElementById("display").value += value;
}
function clearDisplay() {
document.getElementById("display").value = "";
}
function calculate() {
var displayValue = document.getElementById("display").value;
var result = eval(displayValue);
document.getElementById("display").value = result;
}
</script>
</body>
</html>
12
Manish raj(2301560122)
Output
13
Manish raj(2301560122)
Q12 JavaScript program to demonstrate the use of var, const and let keywords.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>var, const, and let Example</title>
</head>
<body>
<h2>var, const, and let Example</h2>
<div id="output"></div>
<script>
// Example using var
var varExample = "This is a var variable";
varExample = "Changed var variable";
Output
14
Manish raj(2301560122)
<script>
// Synchronous function
function synchronousFunction() {
return "Synchronous operation completed.";
}
// Asynchronous function
function asynchronousFunction(callback) {
setTimeout(function() {
callback("Asynchronous operation completed.");
}, 2000); // Simulate delay of 2 seconds
}
// Synchronous operation
var syncResult = synchronousFunction();
document.getElementById('syncResult').innerText = "Synchronous Result: " + syncResult;
// Asynchronous operation
asynchronousFunction(function(result) {
document.getElementById('asyncResult').innerText = "Asynchronous Result: " + result;
});
</script>
</body>
</html>
Output
15
Manish raj(2301560122)
Q14 JavaScript program to show Exception Handling (with use of try, catch and throw)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exception Handling Example</title>
</head>
<body>
<h2>Exception Handling Example</h2>
<button id="triggerError">Trigger Error</button>
<p id="errorMessage"></p>
<script>
// Add event listener to the button
document.getElementById('triggerError').addEventListener('click', function() {
try {
// This code intentionally throws an error
throw new Error('This is a custom error message.');
} catch (error) {
// Catch the error and display it in the DOM
document.getElementById('errorMessage').innerText = 'Error Message: ' + error.message;
}
});
</script>
</body>
</html>
Output
16
Manish raj(2301560122)
Q15 JavaScript program to demonstrate a Document Object Model (DOM). Show use of the
methods of a document object i.e.
getElementById(),getElementsByName(),getElementsByTagName(),
getElementsByClassName().
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Methods Example</title>
</head>
<body>
<h2>DOM Methods Example</h2>
<!-- Sample elements for demonstration purposes -->
<div id="myDiv">This is a div element with id "myDiv"</div>
<input type="text" name="username" placeholder="Enter username">
<p>This is paragraph 1 with class "paragraph"</p>
<p>This is paragraph 2 with class "paragraph"</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
// Accessing elements by ID
var divElement = document.getElementById('myDiv');
console.log('Element by ID:', divElement);
// Accessing elements by name
var usernameInput = document.getElementsByName('username')[0]; // Assuming there's
only one element with this name
console.log('Element by Name:', usernameInput);
// Accessing elements by tag name
var paragraphElements = document.getElementsByTagName('p');
console.log('Elements by Tag Name:', paragraphElements);
// Accessing elements by class name
var paragraphsWithClass = document.getElementsByClassName('paragraph');
console.log('Elements by Class Name:', paragraphsWithClass);
</script>
</body>
</html>
Output
17
Manish raj(2301560122)
18
Manish raj(2301560122)
<script>
// Add an event listener to the button
document.getElementById('myButton').addEventListener('click', function() {
// This function is called when the button is clicked
var button = document.getElementById('myButton');
if (button.textContent === 'Click Me!') {
button.textContent = 'Button Clicked!';
} else {
button.textContent = 'Click Me!';
}
});
</script>
</body>
</html>
Output
19
Manish raj(2301560122)
Q17 JavaScript program with function that finds the longest word in a sentence.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Longest Word</title>
</head>
<body>
<h2>Find Longest Word</h2>
<p>The longest word in the sentence "The quick brown fox jumped over the lazy dog" is:
<span id="result"></span></p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var sentence = "The quick brown fox jumped over the lazy dog"; // Example sentence
var result = findLongestWord(sentence);
document.getElementById('result').innerText = result;
});
function findLongestWord(sentence) {
// Split the sentence into an array of words
var words = sentence.split(" ");
var longestWord = '';
// Iterate through the words to find the longest one
for (var i = 0; i<words.length; i++) {
var word = words[i];
// Remove any punctuation marks from the word
word = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
if (word.length>longestWord.length) {
longestWord = word;
}
}
return longestWord;
}
</script>
</body>
</html>
Output
20
Manish raj(2301560122)
Q18 JavaScript program with a given an array containing numbers from 1 to N, with one
number missing, find the missing number.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Missing Number</title>
</head>
<body>
<h2>Find Missing Number</h2>
<p>The missing number in the array [1, 2, 3, 4, 6, 7, 8, 9, 10] is: <span
id="result"></span></p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var arr = [1, 2, 3, 4, 6, 7, 8, 9, 10]; // Example array
var result = findMissingNumber(arr);
document.getElementById('result').innerText = result;
});
function findMissingNumber(arr) {
var n = arr.length + 1; // Total number of elements if no number was missing
var sum = (n * (n + 1)) / 2; // Sum of numbers from 1 to N
// Calculate the sum of elements in the array
var arrSum = arr.reduce(function(a, b) {
return a + b;
}, 0);
// The difference between the sum of elements from 1 to N and the sum of elements in the
array
var missingNumber = sum - arrSum;
return missingNumber;
}
</script>
</body>
</html>
Output
21
Manish raj(2301560122)
Q19 JavaScript program to find the First Non-Repeated Character in given string
‘aabbccddeeffg’
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find First Non-Repeated Character</title>
</head>
<body>
<h2>Find First Non-Repeated Character</h2>
<p>The first non-repeated character in the string 'aabbccddeeffg' is: <span
id="result"></span></p>
<script>
document.addEventListener('DOMContentLoaded', function() {
var str = 'aabbccddeeffg';
var result = findFirstNonRepeatedCharacter(str);
document.getElementById('result').innerText = result;
});
function findFirstNonRepeatedCharacter(str) {
var charCount = {};
// Count occurrences of each character in the string
for (var i = 0; i<str.length; i++) {
var char = str[i];
if (charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
// Find the first non-repeated character
for (var j = 0; j <str.length; j++) {
var char = str[j];
if (charCount[char] === 1) {
return char;
}
}
return null; // If no non-repeated character found
}
</script>
</body>
</html>
Output
22
Manish raj(2301560122)
23
Manish raj(2301560122)
Q20 JavaScript program to create a calculator with basic operations of addition, subtraction,
multiplication and division
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Simple Calculator</title>
<style>
input[type="button"] {
width: 50px;
height: 50px;
font-size: 20px;
}
</style>
</head>
<body>
<h2>Simple Calculator</h2>
<input type="text" id="display" disabled /><br /><br />
<input type="button" value="1" onclick="appendToDisplay('1')" />
<input type="button" value="2" onclick="appendToDisplay('2')" />
<input type="button" value="3" onclick="appendToDisplay('3')" />
<input type="button" value="+" onclick="appendToDisplay('+')" /><br /><br />
<input type="button" value="4" onclick="appendToDisplay('4')" />
<input type="button" value="5" onclick="appendToDisplay('5')" />
<input type="button" value="6" onclick="appendToDisplay('6')" />
<input type="button" value="-" onclick="appendToDisplay('-')" /><br /><br />
<input type="button" value="7" onclick="appendToDisplay('7')" />
<input type="button" value="8" onclick="appendToDisplay('8')" />
<input type="button" value="9" onclick="appendToDisplay('9')" />
<input type="button" value="*" onclick="appendToDisplay('*')" /><br /><br />
<input type="button" value="C" onclick="clearDisplay()" />
<input type="button" value="0" onclick="appendToDisplay('0')" />
<input type="button" value="=" onclick="calculate()" />
<input type="button" value="/" onclick="appendToDisplay('/')" /><br /><br />
<script>
function appendToDisplay(value) {
document.getElementById("display").value += value;
}
function clearDisplay() {
document.getElementById("display").value = "";
}
function calculate() {
var displayValue = document.getElementById("display").value;
var result = eval(displayValue);
document.getElementById("display").value = result;
}
</script>
</body>
</html>
24
Manish raj(2301560122)
Output
25