0% found this document useful (0 votes)
6 views

Practical File[1]

The document contains a series of JavaScript code snippets that demonstrate various programming concepts, including swapping values, calculating areas, checking for vowels, and handling user input. Each code snippet is presented within an HTML structure and includes comments on expected input and output. The document serves as a practical guide for learning JavaScript through examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Practical File[1]

The document contains a series of JavaScript code snippets that demonstrate various programming concepts, including swapping values, calculating areas, checking for vowels, and handling user input. Each code snippet is presented within an HTML structure and includes comments on expected input and output. The document serves as a practical guide for learning JavaScript through examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Q1.

Write a code snippet in javaScript to swap values of


two numbers. (2 ways)
Code:
<html>
<head>
<title>swap method 1</title>
</head>
<body>
<script>
var a=5;
var b=10;
document.write("before swap: a =", a, ",b =", b);
var temp = a;
a=b;
b=temp;
document.write("After swap: a =", a, ",b =", b);
</script>
</body> </html>

Output:

<html>
<head>
<title>swap method 2.</title>
</head>
<body>
<script>
var a=5;
var b=10;
document.write("before swap: a=", a,",b=",b);
[a,b] = [b,a];
document.write("After swap: a=", a,",b=",b);
</script>
</body></html>
Output: same
Q2. Write a code snipped in javascript which input 2
numbers and display the square of largest number
among them. (using ternary operator)
Code:
<html>
<head><title>Q2</title>
</head>
<body>
<script>
var num1= parseInt(prompt("enter first number"));
var num2= parseInt(prompt("enter second number"));
let squareOfLargest = (num1 > num2 ? num1 : num2)**2;
document.write("the square of the largest number is:",
squareOfLargest);
</script>
</body>
</html>

Input:
Enter first number: 6
Enter second number 7

Output:
Q3. Write a code snipped in javascript which input an
alphabet and check whether it is a vowel or not.
Code:
<html>
<head><title>Q3</title>
</head>
<body>
<script>
var alphabet=parseInt(prompt("enter a vowel"));
switch(alphabet) {
case"a":
case"e":
case"i":
case"o":
case"u":
document.write(alphabet+ "is a vowel.");
break;
default:
document.write(alphabet+"is not a vowel.");

}
</script>
</body>
</html>

Output:

Q4. write a menu driven code in javascript used to


calculate the area of square , triangle and cuboid.(use
switch case)
Code:
<html>
<head><title>Q4</title>
</head>
<body>
<script>
function calculateArea() {
var choice = parseInt(prompt("Choose an option to
calculate the area:\n1. Square\n2. Triangle\n3. Cuboid"));
switch (choice) {
case 1:
var side = parseFloat(prompt("Enter the length of
the side of the square:"));
var areaSquare = side * side;
document.write("The area of the square is:",
areaSquare);
break;
case 2:
var base = parseFloat(prompt("Enter the base of
the triangle:"));
var height = parseFloat(prompt("Enter the height
of the triangle:"));
var areaTriangle = 0.5 * base * height;
document.write("The area of the triangle is:",
areaTriangle);
break;
case 3:
var length = parseFloat(prompt("Enter the length
of the cuboid:"));
var width = parseFloat(prompt("Enter the width of
the cuboid:"));
var heightCuboid = parseFloat(prompt("Enter the
height of the cuboid:"));
var areaCuboid = 2 * (length * width + width *
heightCuboid + heightCuboid * length);
document.write("The surface area of the cuboid
is:", areaCuboid);
break;
default:
document.write("Invalid choice. Please select a
valid option.");
}
}
calculateArea();

</script>
</body>
</html>
Input:
Choose an option: 1(square)
Enter the side of the square:25
Output:

Q5.write a code snipped in javascript which input


quantity and price of an item. Calculate the net amount
which is after deducting discount from total . discount is
15% of total . total amount is quantity*price.
Code:
<html>
<head><title>Q5</title>
</head>
<body>
<script>
var quantity = parseInt(prompt("Enter the quantity of the
item:"));
var price = parseInt(prompt("Enter the price of the
item:"));
var totalAmount = quantity * price;
var discount = 0.15 * totalAmount;
var netAmount = totalAmount - discount
document.write("Total Amount: " + totalAmount +
"<br>");
document.write("Discount (15%): " + discount + "<br>");
document.write("Net Amount after Discount: " +
netAmount);
</script>
</body>
</html>
input:
Enter the quantity of the item: 50
Enter the price of the item :100
Output:
Q6.write a code snipped in javascript which input basic
salary of an employ and calculate the gross salary which
is basic +HRA+DA. Where HRA and DA is to be calculate
on following basis:
BASIC HRA(% OF BASIC) DA(% OF BASIC)
<=15000 5% 7%
>15000 10% 15%

Code:
<html>
<head><title>Q6</title>
</head>
<body>
<script>
var basicSalary = parseInt(prompt("Enter the basic salary
of the employee:"));
var hraPercentage = basicSalary <= 15000 ? 0.05 : 0.10;
var daPercentage = basicSalary <= 15000 ? 0.07 : 0.15;
var hra = basicSalary * hraPercentage;
var da = basicSalary * daPercentage;
var grossSalary = basicSalary + hra + da;
document.write("Basic Salary: " + basicSalary + "<br>");
document.write("HRA: " + hra + "<br>");
document.write("DA: " + da + "<br>");
document.write("Gross Salary: " + grossSalary);
</script>
</body>
</html>
Input:
Enter the basic salary: 13000
Output:

Q7.write a code snippet in javascript to print Fibonacci


series.
Code:
<html>
<head><title>Q7</title>
</head>
<body>
<script>
var n;
var i,c;
var a=0;
var b=1;
n=parseInt(prompt("enter a number"));
for(i=1; i<=n; i++)
{
c=a+b;
a=b;
b=c;
document.write(c);
}
</script>
</body>
</html>
Input:
Enter a number :7
Output:
Q8.write a code snippet in javascript to print factorial of a
number.
Code:
<html>
<head><title>Q8</title>
</head>
<script>
var n=parseInt(prompt("enter a number"));
var p=1;
var i;
for (i=n;i>=1;i--)
{
p=p*i;
}
document.write("the factorial is"+n);
</script>
</body>
</html>

Output:
Q9.write a code snippet in javascript to check whether
number is prime or not.
Code:
<html>
<head><title>Q9</title>
</head>
<body>
<script>
var n = parseInt(prompt("Enter a number to check if it is
prime:"));
var i;
for (i = 2; i <= n - 1; i++) {
if (n % i === 0) {
document.write("It is not a prime number");
break;
} else {
document.write("It is a prime number");
}
}
</script>
</body>
</html>
Input:
Enter the number: 8
Output:

Q10.write a javascript program for a text in a string and


return the text if found using match().
Code:
<html>
<head><title>q10</title></head>
<body>
<script>
</body>
</html>

Output:
Q11. Write a code snippet in javascript to display an array
of size 6. After displaying the array remove the last
element.
Code:
<html>
<head>
<title>Q11</title>
</head>
<body>
<script>
const number=[10, 20, 30, 40, 50, 60];
document.write("Original array:", number +"<br>");
number.pop();
document.write("Array after removing the last
element:",number);
</script>
</body>
</html>

Output:

Q12. Write a function which accepts array as a parameter


and sorts that array of integers in ascending order using
the sort method.
Code:
<html>
<head>
<title>Q12</title>
</head>
<body>
<script>
function sortArray(arr){
arr.sort(function(a,b){
return a-b;
});
document.write("sorted array in ascending order."+ arr);
}
const number=["6","0","9","4","3","8"];
sortArray(number);
</script>
</body>
</html>
Output:

Q13.write a function that takes two numbers as


parameters and returns their sum. Test your function
with different input values.
Code:
<html>
<head>
<title>Q13</title>
</head>
<body>
<script>
function addNumbers(num1,num2)
{
return num1+num2;
}
document.write("sum of 5 and
3:",addNumbers(5,3)+"<br>");
document.write("sum of 10 and
15:",addNumbers(10,15)+"<br>");
document.write("sum of 4 and
6:",addNumbers(4,6)+"<br>");
document.write("sum of 0 and
0:",addNumbers(0,0)+"<br>");

</script>
</body>
</html>
Output:

Q14.write a program with 2 function to find simple or


compound interest depending on user input also take
user input for principal ,rate and time.
Simple interest: (P*R*T)/100
Compound interest: A=P(1+r/100)t.
Code:
<html>
<head>
<title>Q14</title>
</head>
<body>
<script>
function calculateSimpleInterest(principal, rate, time) {
return (principal * rate * time) / 100;
}
function calculateCompoundInterest(principal, rate, time)
{
return principal * Math.pow((1 + rate/100), time);
}

function getUserInputs() {
const principal = parseInt(prompt("Enter the principal
amount:"));
const rate = parseInt(prompt("Enter the rate of interest
(in %):"));
const time = parseInt(prompt("Enter the time
period:"));
const interestType = prompt("Enter the type of interest
(simple/compound):").toLowerCase();

if (interestType === "simple") {


alert("The simple interest is: " +
calculateSimpleInterest(principal, rate, time));
} else if (interestType === "compound") {
alert("The compound interest is: " +
calculateCompoundInterest(principal, rate, time));
} else {
alert("Invalid interest type entered. Please choose
either 'simple' or 'compound'.");
}
}
getUserInputs();
</script>
</body>
</html>
Input:
Enter the principal amount:50
Enter the rate of interest(in%): 60%
Enter the time period : 2hours
Enter the type of interest (simple/compound):simple.
Output:

Q15.write a javaScript code to sort an array.


Code:
<html>
<head>
<title>Q15</title>
</head>
<body>
<script>
const number=["0","6","9","4","7"];
var a= number.sort();
document.write(a);
</script>
</body>
</html>
Output:

Q16.write a program where function MyFunc() it takes


the user name and display a message “Hello username
welcome to this page”.
Code:
<html>
<head>
<title>Q16</title>
<script type="text/javascript">
function MyFunc() {
var userName =
document.getElementById("username").value;
document.getElementById("message").innerHTML =
"Hello " + userName + ", welcome to this page!";
}
</script>
</head>
<body>
<h2>Enter your name:</h2>
<input type="text" id="username" placeholder="Enter
your name">
<button onclick="MyFunc()">Submit</button>
<p id="message"></p>
</body>
</html>
Output:
Q17.write a code to generate the following output:
S
Se
Seni Senio
Senior.
Code:
<html>
<head><title>Q17</title>
</head>
<body>
<script>
let word="Senior".split("");
let result="";

for (let i=1; i<=word.length; i++){


let sliced = word.slice(0,i);
result += sliced.join("")+" ";
}
document.write(result);
</script>
</body>
</html>
Output:
Q18. write a program with function to find the smallest
out of 3 numbers.
Code:
<html>
<head><title>Q18</title>
</head>
<script>
function findSmallest(a,b,c)
{
if(a<=b && a<=c) return a;
if(b<=a && b<=c) return b;
return c;
}
let num1 = prompt("enter first number");
let num2 = prompt("enter second number");
let num3 = prompt("enter third number");
let smallest = findSmallest(parseInt(num1),
parseInt(num2),parseInt(num3));
document.write("smallest number."+smallest);
</script>
</html>
Input:
Enter first number:10
Enter first number:5
Enter first number:15
Output:
Q19.write a javascript code to insert a new element in an
array.
Code:
<html>
<head><title>Q19</title>
</head>
<script>
function findSmallest(a,b,c)
{
if(a<=b && a<=c) return a;
if(b<=a && b<=c) return b;
return c;
}
let num1 = prompt("enter first number");
let num2 = prompt("enter second number");
let num3 = prompt("enter third number");
let smallest = findSmallest(parseInt(num1),
parseInt(num2),parseInt(num3));
document.write("smallest number."+smallest);
</script>
</html>
Output:
Q20. Write a program with a function to take user input
in kilograms and convert it to grams.[1 kilogram =100
grams]
Code:
<html>
<head><title>Q20</title>
</head>
<script>
let kg= prompt("enter weight in kilograms.");
let grams= kg*1000;
alert(kg +"kilograms is equal to"+grams+ "grams.");
</script>
</html>

Input:
Enter weight in kilograms: 8
Output:
Q21.write a program with function sortnum() to sort 3
numbers in asending order.
Code:
<html>
<head><title>Q21</title>
</head>
<script>
function sortnum(a,b,c){
if(a>b){
[a,b]=[b,a];
}
if(a>c){
[a,c]=[c,a];
}
if(b>c){
[b,c]=[c,b];
}
return[a,b,c];
}
let num1= prompt("enter first number");
let num2= prompt("enter second number");
let num3= prompt("enter third number");

let sortedNums =
sortnum(parseInt(num1),parseInt(num2),parseInt(num3)
);
document.write("sorted numbers:" + sortedNums);
</script>
</html>

Input:
Enter first number=9
Enter second number=1
Enter third number=5
Output:

Q22.write a code snippet in javascript that shows the


usage of join(), pop(), slice(), splice(), unshift(), method.
Code:
<html>
<head><title>Q22</title>
</head>
<script>
const colors=["Red","green","blue","yellow"];
document.write("original array:",colors);
//join()
document.write("JOIN:",colors.join());
//pop()
colors.pop();
document.write("POP:",colors);
//slice()
let newcolors=colors.slice(1);
document.write("SLICE:",newcolors);
//splice()
colors.splice(1,0,"purple");
document.write("SPLICE:",colors);
//unshift()
colors.unshift("orange");
document.write("UNSHIFT:",colors);
</script>
</html>
Output:
Q23.write a code snippet in javascript that generates a
random number between a specified range using the
math.random() method. Also write the code to show the
usage of math() and math.min().
Code:
<html>
<head><title>Q23</title>
</head>
<script>
let randomNumber = Math.floor(Math.random()*100)+1;
document.write("Random number.",randomNumber);
//math()
document.write("ceilling of 4.7",Math.ceil(4.7));
document.write("floor of 4.7",Math.floor(4.7));
document.write("Round of 4.7",Math.round(4.7));
//math min()
let numbers = [12,5,8,20,3];
document.write("smallest Number.",
Math.min(...numbers));
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
let min = 50;
let max = 150;
document.write ("Random Number between", min,
"and",max,":",getRandomNumber(min,max));
</script>
</html>
Output:
Q24.using a button call a function pytha() and takes the
input for the sides then check whether a number is a
pythagorean triplet or not.
Hint: pythagorean triplet are a2+b2=c2 where a , b and c
are the three positive integers.
Code:
<html>
<head>
<title>Q24.Pythagorean Triplet Checker</title>
</head>
<body>
<h2>Pythagorean Triplet Checker</h2>

<input id="side1" type="number" placeholder="Side 1">


<input id="side2" type="number" placeholder="Side 2">
<input id="side3" type="number" placeholder="Side 3">

<button onclick="pytha()">Check</button>

<p id="result"></p>

<script>
function pytha() {
let a =
parseInt(document.getElementById("side1").value);
let b =
parseInt(document.getElementById("side2").value);
let c =
parseInt(document.getElementById("side3").value);

if (a*a + b*b == c*c) {


document.getElementById("result").innerHTML = "Yes,
it's a Pythagorean triplet!";
} else if (b*b + c*c == a*a) {
document.getElementById("result").innerHTML = "Yes,
it's a Pythagorean triplet!";
} else if (a*a + c*c == b*b) {
document.getElementById("result").innerHTML = "Yes,
it's a Pythagorean triplet!";
} else {
document.getElementById("result").innerHTML = "No,
it's not a Pythagorean triplet.";
}
}
</script>
</body>
</html>
Input:
Side1: 3
Side2: 4
Side3: 5
Output:

Q25.Declare a function “stringjava” in javascript to accept


two strings arguments. The function should :
• Convert both the strings to lowercase
• Search for string1 in string2 and display the string if
found.
• Replace all occurrences of letter “I” with “!” in
string2.
• Display first character of string1.
Code:
<html>
<head><title>Q25.JavaScript String Function</title>
</head>
<body>
<h2>JavaScript String Function</h2>
<input id="str1" type="text" placeholder="Enter String
1">
<input id="str2" type="text" placeholder="Enter String
2">
<button onclick="stringjava()">Run Function</button>
<div id="result"></div>

<script>
function stringjava() {
let str1 = document.getElementById("str1").value;
let str2 = document.getElementById("str2").value;
// Convert to lowercase
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
let result = "";
// Search for str1 in str2
if (str2.includes(str1)) {
result += str1 + " found in String 2<br>";
} else {
result += str1 + " not found in String 2<br>";
}
// Replace "i" with "!" in str2
str2 = str2.replace(/i/g, "!");
result += "Modified String 2: " + str2 + "<br>";
// Display first character of str1
result += "First character of String 1: " + str1[0];
document.getElementById("result").innerHTML = result;
}
</script>
</body>
</html>
Input:
Enter string1: “hello”
Enter string2: "this is hello world"
Output:

Q26 .Consider the following code:


Var cars=[“Honda”,” “BMW”, “Audi”, “porsche”];
Write command in javascript to:
• Add an item “volvo” to the array cars in the last.
• Remove first element from the array.
• Add following array to an array “cars”
Var person=[“ranjan”,”yagya”, “munish”];

Code:
<html>
<head><title>Q26.</title>
</head>
<body>
<script>
const cars=["Honda","BMW","Audi","porsche"];
document.write("Original array:<br>",cars);
{
cars.push("volvo");
document.write("<br>a)Adding volvo in the
array:<br>",cars);
}
{
cars.shift();
document.write("<br>b)After removing first element
from the array:<br>",cars);
}
</script>
</body>
</html>
Output:

Q27. Consider the string “life is Beautiful”. Write a


function “mystring” that performs the following tasks:
• Display the length of the string
• Display the string after replacing space “” in the
string with “*”
• Find the position of the first occurrence of “if” and
display it.
code:
<html>
<head>
<title>Q27.JavaScript String Function</title>
</head>
<body>
<h2>JavaScript String Function</h2>
<input id="str" type="text" value="life is beautiful">
<button onclick="mystring()">Run Function</button>
<div id="result"></div>
<script>
function mystring() {
let str = document.getElementById("str").value;
// a) Display the length of the string
let length = str.length;
let result = "String: " + str + "<br>";
result += "Length of the string: " + length + "<br>";

// b) Display the string after replacing space with "*"


let replacedStr = str.replace(/ /g, "*");
result += "String after replacing space with '*': " +
replacedStr + "<br>";

// c) Find the position of the first occurrence of "if"


let position = str.indexOf("if");
result += "Position of the first occurrence of 'if': " +
position;

document.getElementById("result").innerHTML =
result;
}
</script>

</body>
</html>
Input:
Enter string: life is beautiful
Output:

Q28.write a function :
• To find the value of a number raised power another
number using Math object method
• To find the sqrt of a numbering using Math object
method.

Code:
<html>
<head><title>Q28.JavaScript Math Functions</title>
</head>
<body>
<h2>JavaScript Math Functions</h2>
<input id="base" type="number"
placeholder="Base">
<input id="exponent" type="number"
placeholder="Exponent">
<button onclick="power()">Calculate
Power</button>
<div id="powerResult"></div>
<input id="number" type="number"
placeholder="Number">
<button onclick="sqrt()">Calculate Square
Root</button>
<div id="sqrtResult"></div>
<script>
// Function to find the value of a number raised to
the power of another number
function power() {
let base = document.getElementById("base").value;
let exponent =
document.getElementById("exponent").value;
let result = Math.pow(base, exponent);
document.getElementById("powerResult").innerHT
ML = base + " raised to the power of " + exponent + "
is: " + result;
}
// Function to find the square root of a number
function sqrt() {
let number =
document.getElementById("number").value;
let result = Math.sqrt(number);
document.getElementById("sqrtResult").innerHTML
= "Square root of " + number + " is: " + result;
}
</script>
</body>
</html>

Input:
Base:2
Exponent:3
Number:16
Output:
Q29. Write a program with a function called through a
button to ask user age if the age is greater than 18,
display the message “you are eligible”.
Code:
html>
<head>
<title>Q29.Age Eligibility Checker</title>
</head>
<body>
<h2>Age Eligibility Checker</h2>
<input id="age" type="number" placeholder="Enter your
age">
<button onclick="checkEligibility()">Check
Eligibility</button>
<div id="result"></div>
<script>
function checkEligibility() {
let age = document.getElementById("age").value;
if (age >= 18) {
document.getElementById("result").innerHTML = "You
are eligible!";
} else if (age < 18 && age >= 0) {
document.getElementById("result").innerHTML = "You
are not eligible. You must be 18 or older.";
} else {
document.getElementById("result").innerHTML =
"Invalid age. Please enter a valid number.";
}
}
</script>
</body>
</html>
Input:
Enter your age:18;

Output:

Q30. Write a program to display an alert box with the


message “welcome to the website” when the webpage is
first loaded.
Code:
<html>
<head>
<title>Q30.Welcome Alert</title>
</head>
<body>
<script>
// Display alert box when webpage loads
window.onload = function() {
alert("Welcome to the website!");
}
</script>
</body>
</html>

Output:

Q31.write a program to display an alert box with the


message “you pressed the key” when a key is pressed.
Code:
<html>
<head>
<title>Q31.Key Press Alert</title>
</head>
<body>
<h1>Press any key</h1>
<script>
document.addEventListener("keydown", function(event)
{
alert("You pressed the"+ event.key + "key!");
});
</script>
</body>
</html>

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy