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

FSD FINAL LAB MANUAL

The document contains multiple HTML programs demonstrating various HTML elements and their functionalities. It includes examples of lists, hyperlinks, images with links, thumbnails, tables, forms, and frames. Each section provides code snippets and explanations for creating structured web content using HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

FSD FINAL LAB MANUAL

The document contains multiple HTML programs demonstrating various HTML elements and their functionalities. It includes examples of lists, hyperlinks, images with links, thumbnails, tables, forms, and frames. Each section provides code snippets and explanations for creating structured web content using HTML.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

1.A a. WriteaHTMLprogram,toexplaintheworkingoflists.

Note:Itshouldhavean ordered list,unordered


list,nestedlistsandorderedlistinanunorderedlistanddefinitionlists.
<!DOCTYPE html>
<htmllang="en">
<head>
<title>Lists in HTML</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
h1 {
color: #333;
}
section {
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Working with Lists in HTML</h1>

<section>
<h2>1. Ordered List</h2>
<p>An ordered list uses numbers or letters to order items:</p>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
</section>

<section>
<h2>2. Unordered List</h2>
<p>An unordered list uses bullet points:</p>
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>
</section>

<section>
<h2>3. Nested Lists</h2>
<p>You can nest lists inside one another:</p>
<ul>
<li>Outer item 1
<ul>
<li>Nested item 1.1</li>
<li>Nested item 1.2</li>
</ul>
</li>
<li>Outer item 2</li>
</ul>
</section>

<section>
<h2>4. Ordered List in an Unordered List</h2>
<p>You can mix list types by placing an ordered list inside an
unordered list:</p>
<ul>
<li>Item A
<ol>
<li>Sub-item A.1</li>
<li>Sub-item A.2</li>
</ol>
</li>
<li>Item B</li>
</ul>
</section>

<section>
<h2>5. Definition List</h2>
<p>A definition list pairs terms with their descriptions:</p>
<dl>
<dt>HTML</dt>
<dd>HyperTextMarkup Language, used to create webpages.</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets, used to style webpages.</dd>
<dt>JavaScript</dt>
<dd>A programming language used to create interactive effects
within web browsers.</dd>
</dl>
</section>
</body>
</html>

1.B Write a HTML program, to explaintheworkingof hyperlinksusing <a>tag and href,targetAttributes.

<!DOCTYPE html>
<htmllang="en">
<head>
<title>Hyperlinks in HTML</title>
</head>
<body>
<h1>Working with Hyperlinks in HTML</h1>

<section>
<h2>1. Basic Hyperlink</h2>
<p>This is a basic hyperlink using the <code>&lt;a&gt;</code> tag and
the <code>href</code> attribute:</p>
<ahref="https://www.google.com">Visit Example Website</a>
</section>

<section>
<h2>2. Open Link in New Tab</h2>
<p>Use the <code>target="_blank"</code> attribute to open the link in
a new tab:</p>
<ahref="https://www.google.com"target="_blank">Open Google in New
Tab</a>
</section>

<section>
<h2>3. Link to an Email Address</h2>
<p>Use <code>mailto:</code> in the <code>href</code> attribute to
create an email link:</p>
<ahref="mailto:someone@example.com">Send an Email</a>
</section>

<section>
<h2>4. Link to a Specific Section in the Same Page</h2>
<p>Create an anchor link to jump to another section of the page:</p>
<ahref="#section5">Go to Section 5</a>
</section>

<section>
<h2>5. Section for Anchor Link</h2>
<pid="section5">This is the section you jumped to using the anchor
link!</p>
</section>

<section>
<h2>6. Downloadable File Link</h2>
<p>Use the <code>download</code> attribute to allow users to download
a file:</p>
<ahref="example-file.txt"download>Download Example File</a>
</section>
</body>
</html>

1.C Create a HTML documentthat has your image andyour friend’s image with a specificheight and width.
Also when clicked on the images it should navigate to their respectiveprofiles.
<!DOCTYPE html>
<htmllang="en">
<head>

<title>Images with Links</title>

</head>
<body>
<h1>Profiles</h1>
<p>Click on the images below to view the respective profiles.</p>

<!-- Your Image -->


<ahref="profile1.html"target="_blank">
<imgsrc="james.webp"alt="Your Image"width="200"height="250">
</a>

<!-- Friend's Image -->


<ahref="profile2.html"target="_blank">
<imgsrc="gvr.jpg"alt="Friend's Image"width="200"height="250">
</a>
</body>

profile1.html

<!DOCTYPE html>
<htmllang="en">
<head>
<title>profile 1</title>
</head>
<body>
<h1>Profiles</h1>
<p>Guido van Rossum is the creator of the Python programming language. He
grew up in the Netherlands and studied at the University of Amsterdam, where
he graduated with a Master's Degree in Mathematics and Computer Science. </p>
</body>
</html>

profile2.html

<!DOCTYPE html>
<htmllang="en">
<head>
<title>profile 1</title>
</head>
<body>
<h1>Profiles 2</h1>
<p>Guido van Rossum is the creator of the Python programming language. He
grew up in the Netherlands and studied at the University of Amsterdam, where
he graduated with a Master's Degree in Mathematics and Computer Science. His
first job after college was as a programmer at CWI, where he worked on the
ABC language, the Amoeba distributed operating system, and a variety of
multimedia projects. During this time he created Python as side project. He
then moved to the United States to take a job at a non-profit research lab in
Virginia, married a Texan, worked for several other startups, and moved to
California. In 2005 he joined Google, where he obtained the rank of Senior
Staff Engineer, and in 2013 he started working for Dropbox as a Principal
Engineer..</p>
</body>

1.D Write a HTMLprogram, in such away that,rather than placing largeimageson a page,the preferred
technique is to use thumbnails by setting the height and width parameters tosomething
liketo100*100pixels.Eachthumbnail imageisalsoalink toa
fullsizedversionoftheimage.Createanimagegalleryusingthistechnique

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Thumbnail Image Gallery</title>

</head>
<body>
<h1>Image Gallery</h1>
<p>Click on a thumbnail to view the full-sized image.</p>

<divclass="gallery">
<!-- Image 1 -->
<ahref="img_forest.jpg"target="_blank">
<imgsrc="img_forest.jpg"alt="Image 1"width="150"height="150">
</a>
<!-- Image 2 -->
<ahref="image_tree.webp"target="_blank">
<imgsrc="image_tree.webp"alt="Image 1"width="150"height="150">
</a>
<!-- Image 3 -->
<ahref="img_forest.jpg"target="_blank">
<imgsrc="img_forest.jpg"alt="Image 1"width="150"height="150">
</a>
<!-- Image 4 -->
<ahref="img_forest.jpg"target="_blank">
<imgsrc="img_forest.jpg"alt="Image 1"width="150"height="150">
</a>

</div>
</body>
</html>
2.A WriteaHTMLprogram,toexplaintheworkingoftables.(usetags:<table>,<tr>,<th>,<td>and
Attributes:border,rowspan,colspan)

<!DOCTYPE html>
<htmllang="en">
<head>

<title>Table Example</title>

</head>
<body>
<h1style="text-align: center;">Table Example</h1>
<tableborder="1">
<!-- Table Header Row -->
<tr>
<throwspan="2">Name</th>
<thcolspan="2">Scores</th>
<throwspan="2">Total</th>
</tr>
<tr>
<th>Math</th>
<th>Science</th>
</tr>
<!-- Table Data Rows -->
<tr>
<td>John</td>
<td>85</td>
<td>90</td>
<td>175</td>
</tr>
<tr>
<td>Jane</td>
<td>92</td>
<td>88</td>
<td>180</td>
</tr>
<tr>
<td>Sam</td>
<td>78</td>
<td>84</td>
<td>162</td>
</tr>
</table>
</body>
</html>
2.B WriteaHTMLprogram,toexplaintheworkingoftablesbypreparingatimetable. (Note: Use <caption> tag to
set the caption to the table & also use cell spacing,cellpadding,border,rowspan,colspan etc.).
<!DOCTYPE html>
<htmllang="en">
<head>
<title>Timetable Example</title>
</head>
<body>
<h1style="text-align: center;">Weekly Timetable</h1>
<tablecellspacing="5"cellpadding="10"border="1">
<caption><strong>Class Timetable</strong></caption>
<tr>
<throwspan="2">Day</th>
<thcolspan="4">Subjects</th>
</tr>
<tr>
<th>9:00 - 10:00</th>
<th>10:00 - 11:00</th>
<th>11:00 - 12:00</th>
<th>12:00 - 1:00</th>
</tr>
<tr>
<td>Monday</td>
<td>Math</td>
<td>English</td>
<td>Science</td>
<td>History</td>
</tr>
<tr>
<td>Tuesday</td>
<td>Geography</td>
<td>Math</td>
<tdrowspan="2">Physical Education</td>
<td>Computer Science</td>
</tr>
<tr>
<td>Wednesday</td>
<td>English</td>
<td>History</td>
<td>Biology</td>
</tr>
<tr>
<td>Thursday</td>
<td>Science</td>
<td>Math</td>
<td>English</td>
<td>Art</td>
</tr>
<tr>
<td>Friday</td>
<td>History</td>
<td>Computer Science</td>
<td>Geography</td>
<td>Math</td>
</tr>
</table>
</body>
</html>
2.C Write a HTML program, to explain the working of forms by designing Registration form.(Note:Includetext
field,passwordfield,number field,dateof birth field,checkboxes,radio buttons, list boxes using
<select>&<option> tags, <text area> and two buttons ie:submit
andreset.Usetablestoprovideabetterview).
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>

</head>
<body>
<h2style="text-align: center;">Registration Form</h2>
<formaction="#"method="post">
<tableborder="1">
<tr>
<thcolspan="2">Fill Your Details</th>
</tr>
<tr>
<td>Full Name:</td>
<td><inputtype="text"name="fullname"placeholder="Enter your
full name"required></td>
</tr>
<tr>
<td>Password:</td>
<td><inputtype="password"name="password"placeholder="Enter
your password"required></td>
</tr>
<tr>
<td>Age:</td>
<td><inputtype="number"name="age"min="1"placeholder="Enter
your age"required></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><inputtype="date"name="dob"required></td>
</tr>
<tr>
<td>Gender:</td>
<td>

<inputtype="radio"name="gender"value="male"id="male"required>
<labelfor="male">Male</label>

<inputtype="radio"name="gender"value="female"id="female"required>
<labelfor="female">Female</label>
</td>
</tr>
<tr>
<td>Languages Known:</td>
<td>

<inputtype="checkbox"name="language"value="english"id="english">
<labelfor="english">English</label>

<inputtype="checkbox"name="language"value="hindi"id="hindi">
<labelfor="hindi">Hindi</label>

<inputtype="checkbox"name="language"value="french"id="french">
<labelfor="french">French</label>
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<selectname="country"required>
<optionvalue="">--Select Your Country--</option>
<optionvalue="usa">USA</option>
<optionvalue="canada">Canada</option>
<optionvalue="india">India</option>
<optionvalue="uk">UK</option>
<optionvalue="australia">Australia</option>
</select>
</td>
</tr>
<tr>
<td>Address:</td>
<td>
<textareaname="address"rows="4"placeholder="Enter your
address"></textarea>
</td>
</tr>
<tr>
<tdclass="buttons"colspan="2">
<inputtype="submit"value="Submit">
<inputtype="reset"value="Reset">
</td>
</tr>
</table>
</form>
</body>
</html>

2.D Write a HTML program, to explain the working of frames, such that page is to be dividedinto 3 parts on
either direction. (Note: first frame image, second frame paragraph,third framehyperlink.And
alsomakesure ofusing“noframe” attributesuchthatframestobefixed).
<!DOCTYPE html>
<html>
<head>
<title>Frameset Example</title>
</head>
<framesetcols="33%, 33%, 34%">
<!-- First frame: Displays an image -->
<framesrc="image_frame.html"name="frame1" />

<!-- Second frame: Displays a paragraph -->


<framesrc="paragraph_frame.html"name="frame2" />

<!-- Third frame: Displays a hyperlink -->


<framesrc="link_frame.html"name="frame3" />

<!-- No Frames Fallback -->


<noframes>
<body>
<p>Your browser does not support frames. Please upgrade your
browser or visit these pages:</p>
<ul>
<li><ahref="image_frame.html">Image Page</a></li>
<li><ahref="paragraph_frame.html">Paragraph Page</a></li>
<li><ahref="link_frame.html">Link Page</a></li>
</ul>
</body>
</noframes>
</frameset>
</html>
image_frame.html

<!DOCTYPE html>
<html>
<head>
<title>Image Frame</title>
</head>
<body>
<h2>Image Frame</h2>
<imgsrc="img_forest.jpg"alt="Sample Image"width="300"height="200">
</body>
</html>
paragraph_frame.html

<!DOCTYPE html>
<html>
<head>
<title>Paragraph Frame</title>
</head>
<body>
<h2>Paragraph Frame</h2>
<p>
This is a demonstration of using frames in HTML. Frames allow you to
divide a browser window into multiple sections, each loading separate HTML
files.
</p>
</body>
</html>
link_frame.html

<!DOCTYPE html>
<html>
<head>
<title>Link Frame</title>
</head>
<body>
<h2>Hyperlink Frame</h2>
<p>
Visit: <ahref="https://www.google.com"target="_blank">Example
Website</a>
</p>
</body>
</html>
3.A WriteaHTMLprogram,thatmakesuseof<article>,<aside>,<figure>,<figcaption>,<footer>,<header>,<main>,<na
v>,<section>,<div>,<span>tags.
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Semantic HTML Example</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
}
header {
background: #333;
color: #fff;
padding: 1rem;
text-align: center;
}
nav {
background: #444;
color: #fff;
padding: 0.5rem;
text-align: center;
}
nav a {
color: #fff;
margin: 0 1rem;
text-decoration: none;
}
main {
display: flex;
flex-wrap: wrap;
padding: 1rem;
}
article {
flex: 2;
padding: 1rem;
background: #f4f4f4;
margin: 1rem;
}
aside {
flex: 1;
padding: 1rem;
background: #ddd;
margin: 1rem;
}
figure {
margin: 1rem 0;
text-align: center;
}
figcaption {
font-style: italic;
}
footer {
background: #333;
color: #fff;
text-align: center;
padding: 1rem;
margin-top: 1rem;
}
</style>
</head>
<body>
<header>
<center> <h1>Welcome to My Website</h1></center>
</header>
<navstyle="flex:1;">
<ahref="#home">Home</a>
<ahref="#about">About</a>
<ahref="#contact">Contact</a>
</nav>
<main>
<article>
<h2>Article Title</h2>
<p>This is the main content area. Here is where the primary
content of the webpage is displayed. You can add more paragraphs, images, and
other elements as needed.</p>
<figure>
<imgsrc="https://via.placeholder.com/400"alt="Placeholder
image">
<figcaption>A placeholder image with a caption.</figcaption>
</figure>
<p>Loremipsumdolor sitamet, consecteturadipiscingelit. Sed do
eiusmodtemporincididuntutlabore et dolore magna aliqua.</p>
</article>

<aside>
<h3>Related Links</h3>
<ul>
<li><ahref="#">Link 1</a></li>
<li><ahref="#">Link 2</a></li>
<li><ahref="#">Link 3</a></li>
</ul>
</aside>
</main>

<footer>
<p>&copy; 2024 My Website. All rights reserved.</p>
</footer>
</body>
</html>
3.B WriteaHTMLprogram,toembedaudioandvideointoHTMLwebpage.

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Audio and Video Embedding</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
text-align: center;
padding: 1rem;
}
audio, video {
margin: 1rem 0;
width: 80%;
max-width: 600px;
}
</style>
</head>
<body>
<header>
<h1>Embedding Audio and Video in HTML</h1>
</header>
<main>
<section>
<h2>Audio Example</h2>
<p>Here is an example of an audio file embedded in this
webpage:</p>
<audiocontrols>
<sourcesrc="audio-example.mp3"type="audio/mpeg">
<sourcesrc="audio-example.ogg"type="audio/ogg">
Your browser does not support the audio element.
</audio>
</section>

<section>
<h2>Video Example</h2>
<p>Here is an example of a video file embedded in this
webpage:</p>
<videocontrols>
<sourcesrc="video-example.mp4"type="video/mp4">
<sourcesrc="video-example.ogg"type="video/ogg">
Your browser does not support the video element.
</video>
</section>
</main>

<footer>
<p>&copy; 2024 My Webpage. All rights reserved.</p>
</footer>
</body>
</html>
3.C Write a program to apply different types (or levels of styles or stylespecificationformats)-
inline,internal,externalstylestoHTMLelements.(identifyselector,propertyandvalue).
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>CSS Styling Example</title>
<!-- External CSS -->
<linkrel="stylesheet"href="styles.css">
<style>
/* Internal CSS */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

header {
background-color: #4CAF50;
color: white;
text-align: center;
padding: 1rem;
}

.content {
padding: 1rem;
}

.highlight {
color: #ff5733;
font-weight: bold;
}

footer {
background-color: #333;
color: white;
text-align: center;
padding: 0.5rem;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<h1>Styling Example: Inline, Internal, and External CSS</h1>
</header>
<mainclass="content">
<h2>Inline Styles</h2>
<pstyle="color: blue; font-size: 18px;">This paragraph uses
<strong>inline styles</strong> to set the text color to blue and increase the
font size.</p>

<h2>Internal Styles</h2>
<pclass="highlight">This paragraph uses a <strong>class
selector</strong> defined in the internal stylesheet to apply specific
styles.</p>

<h2>External Styles</h2>
<pclass="external">This paragraph uses styles defined in an external
stylesheet. Check the linked <code>styles.css</code> file for details.</p>
</main>
<footer>
<p>&copy; 2024 Styling Example. All rights reserved.</p>
</footer>
</body>
</html>
4.A <!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>CSS Selector Types</title>
<linkrel="stylesheet"href="style.css">
</head>
<body>
<!-- Element Selector -->
<h1>Element Selector Example</h1>
<p>This is a paragraph styled using an element selector.</p>

<!-- ID Selector -->


<divid="unique-box">This div is styled using an ID selector.</div>

<!-- Class Selector -->


<divclass="highlight">This div is styled using a class selector.</div>
<spanclass="highlight">This span is also styled using the same class
selector.</span>

<!-- Group Selector -->


<h2>Grouped Selector Example</h2>
<h3>This heading shares styles with the previous heading through a group
selector.</h3>

<!-- Universal Selector -->


<divclass="container">
<p>All elements inside this div are styled using a universal
selector.</p>
<button>Click Me</button>
</div>
</body>
</html>
style.css
/* Element Selector */
h1 {
color: blue;
text-align: center;
}

/* ID Selector */
#unique-box {
background-color: lightgreen;
border: 2pxsolidgreen;
padding: 10px;
width: fit-content;
margin: 10pxauto;
}
/* Class Selector */
.highlight {
color: white;
background-color: orange;
padding: 5px;
border-radius: 5px;
}
/* Group Selector */
h2, h3 {
color: darkred;
font-family: 'Arial', sans-serif;
}
/* Universal Selector */
.container* {
font-style: italic;
color: purple;
}

4.B Combinatorselector(descendant,child,adjacentsibling,generalsibling)

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>CSS Combinator Selectors</title>
<linkrel="stylesheet"href="style2.css">
</head>
<body>
<divclass="container">
<h1>Main Heading</h1>
<pclass="intro">This is an introductory paragraph.</p>
<divclass="child-container">
<h2>Child Heading</h2>
<p>This is a child paragraph inside the child container.</p>
</div>
<h2>Another Heading</h2>
<pclass="sibling">This paragraph is a general sibling of the second
heading.</p>
<p>This paragraph is an adjacent sibling of the second heading.</p>
</div>
</body>
</html>
4.C Pseudo-classselector

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Pseudo-class Selector Example</title>
<style>
/* Pseudo-class for hover effect */
button:hover {
background-color: #4CAF50;
color: white;
}

/* Pseudo-class for nth-child */


ulli:nth-child(odd) {
background-color: #f0f0f0;
}

ulli:nth-child(even) {
background-color: #d0d0d0;
}

/* Pseudo-class for focus */


input:focus {
border: 2px solid blue;
outline: none;
}

/* Pseudo-class for first child */


ulli:first-child {
font-weight: bold;
color: #ff0000;
}
</style>
</head>
<body>
<h1>Pseudo-class Selector Demonstration</h1>

<h2>Hover Effect</h2>
<button>Hover over me!</button>

<h2>nth-child Selector</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<h2>Focus Effect</h2>
<inputtype="text"placeholder="Click to focus" />
</body>
</html>

4.D Pseudo-elementselector

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Pseudo-Element Selector Example</title>
<style>
/* Styling a block element with ::before and ::after */
.title {
font-family: Arial, sans-serif;
font-size: 24px;
color: #333;
position: relative;
margin: 20px 0;
}

/* Adding content before the title using ::before */


.title::before {
content: "→ ";
color: #007BFF;
font-weight: bold;
}

/* Adding content after the title using ::after */


.title::after {
content: " 🌟";
color: gold;
}

/* Styling the first letter of a paragraph using ::first-letter */


.content::first-letter {
font-size: 2em;
font-weight: bold;
color: #FF5733;
}

/* Styling the first line of a paragraph using ::first-line */


.content::first-line {
font-style: italic;
text-decoration: underline;
}
</style>
</head>
<body>
<h1class="title">Welcome to Pseudo-Elements</h1>
<pclass="content">
Pseudo-elements are a powerful feature in CSS that enable you to style
specific parts of elements without adding additional markup to your HTML.
</p>
</body>
</html>
5.A WriteaprogramtodemonstratethevariouswaysyoucanreferenceacolorinCSS.

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Color References in CSS</title>
<style>
/* Named Color */
.named-color {
background-color: coral;
}

/* Hexadecimal Color */
.hex-color {
background-color: #3498db;
}

/* RGB Color */
.rgb-color {
background-color: rgb(46, 204, 113);
}
/* RGBA Color (with transparency) */
.rgba-color {
background-color: rgba(241, 85, 127, 0.7);
}
/* HSL Color */
.hsl-color {
background-color: hsl(120, 100%, 25%);
}

/* HSLA Color (with transparency) */


.hsla-color {
background-color: hsla(120, 100%, 25%, 0.5);
}
</style>
</head>
<body>
<h1>Demonstrating Different Color References in CSS</h1>

<divclass="named-color">
<p>Named Color: coral</p>
</div>
<divclass="hex-color">
<p>Hex Color: #3498db</p>
</div>
<divclass="rgb-color">
<p>RGB Color: rgb(46, 204, 113)</p>
</div>
<divclass="rgba-color">
<p>RGBA Color: rgba(241, 85, 127, 0.7)</p>
</div>
<divclass="hsl-color">
<p>HSL Color: hsl(120, 100%, 25%)</p>
</div>
<divclass="hsla-color">
<p>HSLA Color: hsla(120, 100%, 25%, 0.5)</p>
</div>
</body>
</html>
5.B WriteaprogramusingthefollowingtermsrelatedtoCSSfontandtext:
i. font-size ii.font-weight iii.font-style
iv.text-decoration v.text-transformation vi.text-alignment

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>CSS Font and Text Example</title>
<style>
/* Style the body */
body {
font-family: Arial, sans-serif;
}

/* Style for header */


h1 {
font-size: 36px; /* Font size */
font-weight: bold; /* Font weight */
font-style: italic; /* Font style */
text-decoration: underline; /* Text decoration */
text-transform: uppercase; /* Text transformation */
text-align: center; /* Text alignment */
color: darkblue;
}

/* Style for paragraph */


p {
font-size: 18px; /* Font size */
font-weight: normal; /* Font weight */
font-style: normal; /* Font style */
text-decoration: none; /* Text decoration */
text-transform: capitalize; /* Text transformation */
text-align: justify; /* Text alignment */
color: black;
}
</style>
</head>
<body>
<h1>Welcome to CSS Styling!</h1>
<p>This is an example of using various CSS properties to style text and
fonts. You can adjust font-size, font-weight, font-style, text-decoration,
text-transformation, and text-alignment to achieve different looks and styles
for your content.</p>
</body>
</html>

5.C Writeaprogram,toexplaintheimportanceofCSSBoxmodelusing
ii. Content ii.Border iii.Margin iv.padding
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>CSS Box Model Demo</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: lightblue;
text-align: center;
line-height: 200px;
font-size: 20px;
border: 5px solid black; /* Border */
padding: 20px; /* Padding */
margin: 30px; /* Margin */
}

.content-box {
background-color: lightgreen;
}
.padding-box {
background-color: lightcoral;
}
.border-box {
background-color: lightyellow;
}
.margin-box {
background-color: lightgray;
}
</style>
</head>
<body>
<divclass="box content-box">
<p>Content</p>
</div>

<divclass="box padding-box">
<p>Padding</p>
</div>

<divclass="box border-box">
<p>Border</p>
</div>

<divclass="box margin-box">
<p>Margin</p>
</div>
</body>
</html>

6.A WriteaprogramtoembedinternalandexternalJavaScriptinawebpage.
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Embedding JavaScript</title>

<!-- External JavaScript file -->


<scriptsrc="external.js"></script><!-- External JS file -->

<style>
body {
font-family: Arial, sans-serif;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Embedding JavaScript Example</h1>

<pid="message">Hello, this is a simple JavaScript example!</p>


<buttononclick="changeText()">Click Me</button>

<!-- Internal JavaScript -->


<script>
// This is internal JavaScript code
functionchangeText() {
document.getElementById('message').textContent="The text has been
changed!";
}
</script>
</body>
</html>
6.B Writeaprogramtoexplainthedifferentwaysfordisplayingoutput.

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Different Ways to Display Output</title>
</head>
<body>

<h1>Different Ways to Display Output in JavaScript</h1>


<p>Below are examples of how to display output on a webpage using
different methods in JavaScript:</p>

<h2>1. Using document.write()</h2>


<p>This method writes directly to the HTML document.</p>
<buttononclick="displayWithWrite()">Click to Display with
document.write()</button>

<h2>2. Using alert()</h2>


<p>This method shows an alert popup with the message.</p>
<buttononclick="displayWithAlert()">Click to Display with
alert()</button>
<h2>3. Using innerHTML</h2>
<p>This method inserts text into a specific HTML element by modifying its
`innerHTML` property.</p>
<divid="output"></div>
<buttononclick="displayWithInnerHTML()">Click to Display with
innerHTML</button>

<h2>4. Using console.log()</h2>


<p>This method logs the output to the browser's console.</p>
<buttononclick="displayWithConsole()">Click to Display with
console.log()</button>
<script>
// Function to display output using document.write()
functiondisplayWithWrite() {
document.write("<h3>This is displayed using
document.write()</h3>");
}
// Function to display output using alert()
functiondisplayWithAlert() {
alert("This is displayed using alert().");
}
// Function to display output using innerHTML
functiondisplayWithInnerHTML() {
document.getElementById("output").innerHTML="<h3>This is
displayed using innerHTML</h3>";
}
// Function to display output using console.log()
functiondisplayWithConsole() {
console.log("This is displayed using console.log(). Check the
browser's console.");
}
</script>
</body>
</html>
6.C Writeaprogramtoexplainthedifferentwaysfortakinginput.
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>JavaScript Input Methods</title>
</head>
<body>
<h2>JavaScript Input Methods</h2>
<!-- Input using HTML form -->
<labelfor="userInput">Enter something:</label>
<inputtype="text"id="userInput">
<buttononclick="formInput()">Submit</button>
<br><br>
<buttononclick="promptInput()">Enter Using Prompt</button>
<script>
// 1. Taking input using prompt (works in browsers)
functionpromptInput() {
letname=prompt("Enter your name:");
if (name) {
alert("Hello, "+name);
console.log("Hello, "+name);
}
}

// 2. Taking input using an HTML form (for web pages)


functionformInput() {
letinputValue=document.getElementById("userInput").value;
alert("You entered: "+inputValue);
console.log("Form Input: "+inputValue);
}
// 3. Using an event listener for real-time input handling
document.getElementById("userInput").addEventListener("input",
function(event) {
console.log("Live input: "+event.target.value);
});
</script>
</body>
</html
6.D Createawebpagewhichusespromptdialogueboxtoaskavoterforhisnameandage.Displaytheinformationinta
bleformatalongwitheitherthevotercanvoteornot.
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Voter Information</title>
<style>
table {
width: 50%;
margin: 20px auto;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: center;
}
.container {
text-align: center;
}
</style>
</head>
<body>
<divclass="container">
<h2>Voter Eligibility</h2>
<buttononclick="getVoterInfo()">Enter Voter Information</button>
<br><br>
<tableid="voterTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Eligibility</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

<script>
functiongetVoterInfo() {
letname=prompt("Please enter your name:");
letage=prompt("Please enter your age:");

if (name&&age) {
age=parseInt(age);

// Check if age is valid


if (isNaN(age)) {
alert("Please enter a valid number for age.");
return;
}
leteligibility=age>=18?"Eligible to Vote":"Not Eligible to
Vote";

// Add data to the table

lettable=document.getElementById("voterTable").getElementsByTagName('tbody')
[0];
letrow=table.insertRow();
row.insertCell(0).textContent=name;
row.insertCell(1).textContent=age;
row.insertCell(2).textContent=eligibility;
} else {
alert("Please enter both your name and age.");
}
}
</script>
</body>
</html>
7.A Writeaprogramusingdocumentobjectpropertiesandmethods.

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Document Object Demo</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
#info { margin-top: 20px; padding: 10px; border: 1px solid black;
background: #f4f4f4; }
.highlight { color: red; font-weight: bold; }
</style>
</head>
<body>

<h1>JavaScript Document Object Model (DOM) Example</h1>


<p>Click the buttons to see various document properties and methods in
action.</p>

<buttononclick="showProperties()">Show Document Properties</button>


<buttononclick="modifyDocument()">Modify Document</button>
<buttononclick="addElement()">Add Element</button>
<buttononclick="replaceElement()">Replace Element</button>
<buttononclick="removeElement()">Remove Element</button>
<buttononclick="writeToDocument()">Write to Document</button>

<divid="info"></div>
<h2>Links in this document:</h2>
<ahref="https://www.google.com"class="site-link">Google</a>
<ahref="https://www.bing.com"class="site-link">Bing</a>

<h2>Images in this document:</h2>


<imgsrc="https://via.placeholder.com/100"alt="Placeholder
Image"class="doc-image">

<h2>Forms in this document:</h2>


<formid="myForm">
<inputtype="text"name="username"placeholder="Enter username">
</form>

<script>
functionshowProperties() {
letinfo=document.getElementById("info");
info.innerHTML=`
<p><strong>Title:</strong>${document.title}</p>
<p><strong>URL:</strong>${document.URL}</p>
<p><strong>Last Modified:</strong>$
{document.lastModified}</p>
<p><strong>Number of Forms:</strong>$
{document.forms.length}</p>
<p><strong>Number of Images:</strong>$
{document.images.length}</p>
<p><strong>Number of Links:</strong>$
{document.links.length}</p>
<p><strong>Cookies:</strong>${document.cookie || "No cookies
set"}</p>
`;
}

functionmodifyDocument() {
document.title="Updated Title";
letlinks=document.getElementsByClassName("site-link");
for (letlinkoflinks) {
link.style.color="blue";
}
}
functionaddElement() {
letnewPara=document.createElement("p");
lettext=document.createTextNode("This is a newly added
paragraph.");
newPara.appendChild(text);
newPara.classList.add("highlight");
document.body.appendChild(newPara);
}
functionreplaceElement() {
letoldElement=document.getElementById("info");
letnewElement=document.createElement("div");
newElement.id="info";
newElement.innerHTML="<p><strong>Replaced Content:</strong> This
section has been replaced!</p>";
document.body.replaceChild(newElement, oldElement);
}
functionremoveElement() {
letelement=document.getElementById("info");
if (element) {
document.body.removeChild(element);
}
}
functionwriteToDocument() {
document.open();
document.write("<h2>Document Write Method Used</h2><p>This
content replaces everything!</p>");
document.close();
}
</script>
</body>
</html>
7.B Writeaprogramusingwindowobjectpropertiesandmethods.

<!DOCTYPE html>
<html>
<head>
<title>Window Object Example</title>
</head>
<body>
<h1>Window Object Properties and Methods</h1>
<buttononclick="openNewWindow()">Open New Window</button>
<buttononclick="closeNewWindow()">Close New Window</button>
<buttononclick="showAlert()">Show Alert</button>
<buttononclick="showConfirm()">Show Confirm</button>
<buttononclick="showPrompt()">Show Prompt</button>
<pid="demo"></p>
<script>
letnewWindow;

functionopenNewWindow() {
newWindow=window.open("", "_blank", "width=200,height=100");
newWindow.document.write("<h1>Hello from new window!</h1>");
}

functioncloseNewWindow() {
if (newWindow) {
newWindow.close();
}
}

functionshowAlert() {
window.alert("This is an alert box!");
}
functionshowConfirm() {
if (window.confirm("Are you sure?")) {
document.getElementById("demo").innerHTML="Confirmed!";
} else {
document.getElementById("demo").innerHTML="Cancelled!";
}
}
functionshowPrompt() {
letperson=window.prompt("Please enter your name:", "Guest");
if (person!=null) {
document.getElementById("demo").innerHTML=
"Hello "+person+"! How are you today?";
}
}
</script>
</body>
</html>
7.C Writeaprogramusingarrayobjectpropertiesandmethods.(SAVE AS JAVASCRIPT PROGRAM)

// Creating an array
letmyArray= [10, 20, 30, 40, 50];

// Using the length property


console.log("Array length:", myArray.length); // Output: 5

// Using the push() method to add an element to the end


myArray.push(60);
console.log("Array after push:", myArray); // Output: [10, 20, 30, 40, 50,
60]

// Using the pop() method to remove the last element


myArray.pop();
console.log("Array after pop:", myArray); // Output: [10, 20, 30, 40, 50]

// Using the shift() method to remove the first element


myArray.shift();
console.log("Array after shift:", myArray); // Output: [20, 30, 40, 50]

// Using the unshift() method to add an element to the beginning


myArray.unshift(5);
console.log("Array after unshift:", myArray); // Output: [5, 20, 30, 40, 50]

// Using the indexOf() method to find the index of an element


console.log("Index of 30:", myArray.indexOf(30)); // Output: 2
// Using the splice() method to remove elements from a specific index
myArray.splice(1, 2); // Removes 2 elements starting from index 1
console.log("Array after splice:", myArray); // Output: [5, 40, 50]

// Using the forEach() method to iterate over the array


myArray.forEach(function(element) {
console.log("Element:", element);
});
// Output:
// Element: 5
// Element: 40
// Element: 50

// Using the map() method to create a new array with modified elements
letnewArray=myArray.map(function(element) {
returnelement*2;
});
console.log("New array after map:", newArray); // Output: [10, 80, 100]

// Using the filter() method to create a new array with filtered elements
letfilteredArray=myArray.filter(function(element) {
returnelement>30;
});
console.log("New array after filter:", filteredArray); // Output: [40, 50]

7.D Writeaprogramusingmathobjectpropertiesandmethods.

// JavaScript program demonstrating Math object properties and methods

// Math Properties
console.log("Math.PI:", Math.PI); // Pi value
console.log("Math.E:", Math.E); // Euler's number
console.log("Math.LN2:", Math.LN2); // Natural log of 2

// Math Methods Demonstration


// Rounding methods
console.log("Math.round(4.6):", Math.round(4.6)); // Rounds to nearest
integer
console.log("Math.ceil(4.3):", Math.ceil(4.3)); // Rounds up
console.log("Math.floor(4.9):", Math.floor(4.9)); // Rounds down
console.log("Math.trunc(4.9):", Math.trunc(4.9)); // Removes decimal part

// Power and Square Root


console.log("Math.pow(2, 3):", Math.pow(2, 3)); // 2^3 = 8
console.log("Math.sqrt(25):", Math.sqrt(25)); // Square root of 25

// Trigonometric functions
console.log("Math.sin(Math.PI / 2):", Math.sin(Math.PI/2)); // Sine of 90
degrees
console.log("Math.cos(0):", Math.cos(0)); // Cosine of 0 degrees
console.log("Math.tan(Math.PI / 4):", Math.tan(Math.PI/4)); // Tangent of 45
degrees

// Logarithms
console.log("Math.log(10):", Math.log(10)); // Natural logarithm of 10
console.log("Math.log10(1000):", Math.log10(1000)); // Base 10 logarithm

// Random number generation


console.log("Math.random():", Math.random()); // Random number between 0 and
1
console.log("Random integer between 1 and 10:", Math.floor(Math.random() *10)
+1);

// Absolute and Sign


console.log("Math.abs(-50):", Math.abs(-50)); // Absolute value
console.log("Math.sign(-10):", Math.sign(-10)); // Returns -1, 0, or 1
depending on sign
// Maximum and Minimum
console.log("Math.max(10, 20, 30):", Math.max(10, 20, 30)); // Largest number
console.log("Math.min(10, 20, 30):", Math.min(10, 20, 30)); // Smallest
number

7.E Writeaprogramusingstringobjectpropertiesandmethods.

// JavaScript program demonstrating String object properties and methods

// String Properties
letstr="Hello, JavaScript!";
console.log("String Length:", str.length); // Length of the string

// String Methods Demonstration

// Case conversion
console.log("Uppercase:", str.toUpperCase()); // Convert to uppercase
console.log("Lowercase:", str.toLowerCase()); // Convert to lowercase

// Character access
console.log("Character at index 7:", str.charAt(7)); // Character at index 7
console.log("Character code at index 7:", str.charCodeAt(7)); // Unicode
value

// Substring extraction
console.log("Substring (7, 17):", str.substring(7, 17)); // Extract substring
console.log("Slice (-10, -1):", str.slice(-10, -1)); // Extract using
negative index
// String search
console.log("Index of 'Java':", str.indexOf("Java")); // Find index of
substring
console.log("Last index of 'a':", str.lastIndexOf("a")); // Last occurrence
console.log("Includes 'Script':", str.includes("Script")); // Check if
substring exists

// Replace and Split


console.log("Replace 'JavaScript' with 'World':", str.replace("JavaScript",
"World")); // Replace substring
console.log("Split by space:", str.split(" ")); // Split string into array

// Trim whitespace
letpaddedStr=" Trim me! ";
console.log("Trimmed string:", paddedStr.trim()); // Remove whitespace

// Repeat and Concatenation


console.log("Repeat string:", str.repeat(2)); // Repeat string twice
console.log("Concatenation:", str.concat(" Welcome!")); // Concatenate
strings

7.F Writeaprogramusingregexobjectpropertiesandmethods.

// JavaScript program demonstrating RegExp object properties and methods

// Creating regular expressions


letregex= /hello/i; // Case-insensitive match for 'hello'
lettestString="Hello, JavaScript! Welcome to regex testing.";

// Test if a match exists


console.log("Regex test:", regex.test(testString)); // Returns true if match
exists

// Execute method to find match details


letmatchResult=regex.exec(testString);
console.log("Regex exec:", matchResult); // Returns match details if found

// String search using regex


console.log("String match:", testString.match(regex)); // Returns matched
value
console.log("String search:", testString.search(regex)); // Returns index of
first match

// Replace using regex


console.log("String replace:", testString.replace(/JavaScript/i, "JS")); //
Replace case-insensitive 'JavaScript' with 'JS'

// Splitting a string using regex


letsentence="apple, banana; orange|grape";
console.log("Split string:", sentence.split(/[ ,;|]+/)); // Split using
multiple delimiters

// Using RegExp properties


letglobalRegex= /e/g;
console.log("Global regex test:", globalRegex.test(testString)); // Test for
multiple occurrences
console.log("All matches:", testString.match(globalRegex)); // Get all
matches

// Using special regex characters


letdigitRegex= /\d+/; // Matches one or more digits
console.log("Digit match:", "Order #12345".match(digitRegex));

7. Writeaprogramusingdateobjectpropertiesandmethods.
G
// JavaScript program demonstrating Date object properties and methods

// Creating Date objects


letcurrentDate=newDate(); // Current date and time
console.log("Current Date:", currentDate);

// Creating a specific date


letspecificDate=newDate(2023, 0, 15, 10, 30, 0); // January 15, 2023,
10:30:00
console.log("Specific Date:", specificDate);

// Getting date components


console.log("Year:", currentDate.getFullYear()); // Get year
console.log("Month:", currentDate.getMonth()); // Get month (0-11)
console.log("Date:", currentDate.getDate()); // Get day of the month
console.log("Day:", currentDate.getDay()); // Get day of the week (0-6)
console.log("Hours:", currentDate.getHours()); // Get hours
console.log("Minutes:", currentDate.getMinutes()); // Get minutes
console.log("Seconds:", currentDate.getSeconds()); // Get seconds

// Setting date components


currentDate.setFullYear(2025);
console.log("Updated Year:", currentDate.getFullYear());

// Formatting date as a string


console.log("Date String:", currentDate.toDateString()); // Readable date
format
console.log("Time String:", currentDate.toTimeString()); // Readable time
format
console.log("ISO String:", currentDate.toISOString()); // ISO format

// Date comparisons
letanotherDate=newDate(2023, 5, 20);
console.log("Date Comparison:", currentDate>anotherDate?"Future Date":"Past
Date");

// Get timestamp
console.log("Timestamp:", currentDate.getTime()); // Milliseconds since Jan
1, 1970

// Date arithmetic
lettomorrow=newDate();
tomorrow.setDate(currentDate.getDate() +1);
console.log("Tomorrow's Date:", tomorrow);

letlastWeek=newDate();
lastWeek.setDate(currentDate.getDate() -7);
console.log("Last Week's Date:", lastWeek);

7.H Writeaprogramtoexplainuser-
definedobjectbyusingproperties,methods,accessors,constructorsanddisplay.
// JavaScript program demonstrating User-Defined Object with Properties,
Methods, Accessors, and Constructor

// Defining a User-Defined Object using Constructor Function


functionPerson(firstName, lastName, age) {
// Properties
this.firstName=firstName;
this.lastName=lastName;
this.age=age;

// Method
this.getFullName=function() {
returnthis.firstName+" "+this.lastName;
};

// Accessor (Getter)
Object.defineProperty(this, 'fullName', {
get:function() {
returnthis.firstName+" "+this.lastName;
}
});

// Accessor (Setter)
Object.defineProperty(this, 'fullName', {
set:function(name) {
letparts=name.split(" ");
this.firstName=parts[0];
this.lastName=parts[1];
}
});
}
// Creating an instance of the Person object
letperson1=newPerson("John", "Doe", 30);

// Displaying properties and methods


console.log("First Name:", person1.firstName);
console.log("Last Name:", person1.lastName);
console.log("Age:", person1.age);
console.log("Full Name (Method):", person1.getFullName());
console.log("Full Name (Accessor):", person1.fullName);

// Modifying property using accessor


person1.fullName="Jane Smith";
console.log("Updated First Name:", person1.firstName);
console.log("Updated Last Name:", person1.lastName);
console.log("Updated Full Name (Accessor):", person1.fullName);

8.A Write a program which asks the user to enter three integers, obtains the numbers from
theuserandoutputsHTMLtextthatdisplaysthelargernumberfollowedbythewords“LARGER NUMBER” in an
information message dialog. If the numbers are equal, outputHTMLtextas “EQUALNUMBERS”.
<body>
<script>
// JavaScript program to compare three integers and display the result in an
alert dialog

// Prompt user for three integers


letnum1=parseInt(prompt("Enter first integer:"));
letnum2=parseInt(prompt("Enter second integer:"));
letnum3=parseInt(prompt("Enter third integer:"));
// Determine the largest number or if they are equal
letmessage;
if (num1===num2&&num2===num3) {
message="<b>EQUAL NUMBERS</b>";
} else {
letlargest=Math.max(num1, num2, num3);
message=`<b>${largest} LARGER NUMBER</b>`;
}
// Display the result in an information dialog
document.body.innerHTML=`<p style='font-size: 20px; color: blue;'>$
{message}</p>`;
</script>
</body>
8.B Writeaprogramtodisplayweekdaysusingswitchcase.

<body>
<script>
// JavaScript program to display week days using switch case
// Prompt user to enter a number (1-7)
letdayNumber=parseInt(prompt("Enter a number (1-7) to get the corresponding
weekday:"));

// Determine the day using switch case


letdayName;
switch (dayNumber) {
case1:
dayName="Sunday";
break;
case2:
dayName="Monday";
break;
case3:
dayName="Tuesday";
break;
case4:
dayName="Wednesday";
break;
case5:
dayName="Thursday";
break;
case6:
dayName="Friday";
break;
case7:
dayName="Saturday";
break;
default:
dayName="Invalid input! Please enter a number between 1 and 7.";
}
// Display the result
document.body.innerHTML="<p style='font-size: 20px; color:
green;'>"+dayName+"</p>";
</script>
</body>

8.C Writeaprogramtoprint1to10numbersusingfor,whileanddo-whileloops.(SAVE AS JAVASCRIPT FILE)

// Using for loop


console.log("Using for loop:");
for (leti=1; i<=10; i++) {
console.log(i);
}
// Using while loop
console.log("Using while loop:");
letj=1;
while (j<=10) {
console.log(j);
j++;
}
// Using do-while loop
console.log("Using do-while loop:");
letk=1;
do {
console.log(k);
k++;
} while (k<=10);

8.D Writea programtoprintdatainobjectusingfor-in,for-eachandfor-ofloops.(SAVE AS JAVASCRIPT FILE)

// JavaScript program to print data in an object using for-in, forEach, and


for-of loops

// Defining an object with sample data


letperson= {
firstName:"John",
lastName:"Doe",
age:30,
profession:"Developer"
};

// Using for-in loop to iterate over object properties


console.log("Using for-in loop:");
for (letkeyinperson) {
console.log(`${key}: ${person[key]}`);
}

// Converting object to an array of entries for forEach


console.log("\nUsingforEach on Object.entries:");
Object.entries(person).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

// Using for-of loop on Object.entries to iterate over key-value pairs


console.log("\nUsing for-of loop on Object.entries:");
for (let [key, value] ofObject.entries(person)) {
console.log(`${key}: ${value}`);
}
8.E Developaprogramtodeterminewhetheragivennumberisan‘ARMSTRONGNUMBER’ or not. [Eg: 153 is an
Armstrong number, since sum of the cube of the digits isequaltothenumberi.e.,13+53+33=153]
<body>
<script>
// program to check an Armstrong number of three digits
letsum=0;
constnumber=parseInt(prompt('Enter a three-digit positive integer: '));
// create a temporary variable
lettemp=number;
while (temp>0) {
// finding the one's digit
letremainder=temp%10;

sum+=remainder*remainder*remainder;

// removing last digit from the number


temp=parseInt(temp/10); // convert float into integer
}
// check the condition
if (sum==number) {
console.log(number+" is an Armstrong number");
}
else {
console.log(number+" is not an Armstrong number.");
}
</script>
</body>
8.F Writea programto display thedenomination of the amount deposited in the bank in termsof 100’s, 50’s,
20’s, 10’s, 5’s, 2’s & 1’s. (Eg: If deposited amount is Rs.163, the outputshouldbe1-100’s,1-50’s,1-10’s,1-
2’s&1-1’s)
<html>
<body>
<script>
// JavaScript program to display the denomination of an amount deposited in
the bank

functioncalculateDenominations(amount) {
letdenominations= [100, 50, 20, 10, 5, 2, 1];
letresult= [];

for (letdenomofdenominations) {
letcount=Math.floor(amount/denom);
if (count>0) {
result.push(`${count} - ${denom}'s`);
amount%=denom;
}
}
returnresult.join(", ");
}

// Prompt user for deposit amount


letdepositAmount=parseInt(prompt("Enter the deposit amount:"));

// Check and display result


document.body.innerHTML=`<p style='font-size: 20px; color:
blue;'>Denominations: ${calculateDenominations(depositAmount)}</p>`;
</script>
</body>
</html>
9.A Designaappropriatefunctionshouldbecalledtodisplay Factorialofthatnumber.(JAVASCRIPT PROGRAM)
.I
functiondisplayFactorial(number) {
if (number<0) {
return"Factorial is not defined for negative numbers.";
} elseif (number===0) {
return"The factorial of 0 is 1.";
} else {
letfactorial=1;
for (leti=1; i<=number; i++) {
factorial*=i;
}
return`The factorial of ${number} is ${factorial}.`;
}
}
// Example usage:
letnum=5;
letresult=displayFactorial(num);
console.log(result); // Output: The factorial of 5 is 120.

9.A Fibonacciseriesuptothatnumber(JAVASCRIPT PROGRAM)


.II
functiondisplayFibonacci(limit) {
leta=0, b=1;
console.log(a);
if (limit>0) {
console.log(b);
}
while (b<=limit) {
lettemp=a+b;
a=b;
b=temp;
if (b<=limit) {
console.log(b);
}
}
}
displayFibonacci(10)
9.A Primenumbersuptothatnumber.
.III
functiondisplayPrimes(upToNumber) {
// Loop through all numbers from 2 to the given number
for (letnum=2; num<=upToNumber; num++) {
letisPrime=true;

// Check if the number is divisible by any number between 2 and its


square root
for (leti=2; i<=Math.sqrt(num); i++) {
if (num%i===0) {
isPrime=false;
break;
}
}
// If the number is prime, print it
if (isPrime) {
console.log(num);
}
}
}
// Example usage:
displayPrimes(50); // This will display prime numbers up to 50

9.A Isitpalindromeornot
.IV
functionisPalindrome(input) {
// Convert the input to a string and remove non-alphanumeric characters
// Also, convert it to lowercase for case-insensitive comparison
constcleanInput=input.toString().replace(/[^a-zA-Z0-9]/g,
'').toLowerCase();

// Reverse the cleaned input and compare it to the original cleaned input
constreversedInput=cleanInput.split('').reverse().join('');

// If the cleaned input is equal to the reversed one, it's a palindrome


returncleanInput===reversedInput;
}
// Example usage:
console.log(isPalindrome("A man, a plan, a canal, Panama")); // true
console.log(isPalindrome("Hello")); // false
console.log(isPalindrome(12321)); // true

9.B Designa HTML havinga textbox andfour buttonsnamed Factorial,Fibonacci,Prime,and Palindrome. When
abutton is pressed an appropriate function shouldbe called todisplay
I. Factorialofthatnumber
II. Fibonacciseriesuptothatnumber
III. Primenumbersuptothatnumber
IV. Isitpalindromeornot

<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0">
<title>Number Operations</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
}
input {
padding: 10px;
font-size: 18px;
width: 200px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
margin: 5px;
cursor: pointer;
}
#result {
font-size: 20px;
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>

<h2>Number Operations</h2>
<inputtype="number"id="numberInput"placeholder="Enter a number">
<br>

<buttononclick="calculateFactorial()">Factorial</button>
<buttononclick="generateFibonacci()">Fibonacci</button>
<buttononclick="findPrimes()">Prime Numbers</button>
<buttononclick="checkPalindrome()">Palindrome</button>

<pid="result"></p>

<script>
// Function to calculate factorial
functioncalculateFactorial() {
letnum=parseInt(document.getElementById("numberInput").value);
if (num<0) {
document.getElementById("result").innerText="Factorial not
defined for negative numbers!";
return;
}
letfact=1;
for (leti=2; i<=num; i++) {
fact*=i;
}
document.getElementById("result").innerText="Factorial: "+fact;
}

// Function to generate Fibonacci series up to given number


functiongenerateFibonacci() {
letnum=parseInt(document.getElementById("numberInput").value);
if (num<1) {
document.getElementById("result").innerText="Enter a positive
number!";
return;
}
letfib= [0, 1];
for (leti=2; fib[i-1] +fib[i-2] <=num; i++) {
fib[i] =fib[i-1] +fib[i-2];
}
document.getElementById("result").innerText="Fibonacci Series:
"+fib.join(", ");
}

// Function to find prime numbers up to given number


functionfindPrimes() {
letnum=parseInt(document.getElementById("numberInput").value);
if (num<2) {
document.getElementById("result").innerText="No prime
numbers!";
return;
}
letprimes= [];
for (leti=2; i<=num; i++) {
letisPrime=true;
for (letj=2; j*j<=i; j++) {
if (i%j===0) {
isPrime=false;
break;
}
}
if (isPrime) primes.push(i);
}
document.getElementById("result").innerText="Prime Numbers:
"+primes.join(", ");
}
// Function to check if the number is a palindrome
functioncheckPalindrome() {
letnum=document.getElementById("numberInput").value;
letreversedNum=num.split("").reverse().join("");
if (num===reversedNum) {
document.getElementById("result").innerText=num+" is a
Palindrome!";
} else {
document.getElementById("result").innerText=num+" is NOT a
Palindrome!";
}
}
</script>
</body>
</html>

9.C Writeaprogramtovalidatethefollowingfieldsinaregistrationpage.
i. Name(startwithalphabetandfollowedbyalphanumericandthelengthshouldnotbelessthan6charac
ters)
ii. Mobile(onlynumbersandlength10digits)
iii. E-mail(shouldcontainformatlikexxxxxxx@xxxxxx.xxx)
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<script>
functionvalidateForm() {
varname=document.getElementById("name").value;
varmobile=document.getElementById("mobile").value;
varemail=document.getElementById("email").value;

varnamePattern= /^[A-Za-z][A-Za-z0-9]{5,}$/;
varmobilePattern= /^\d{10}$/;
varemailPattern= /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;

if (!namePattern.test(name)) {
alert("Invalid Name: Must start with an alphabet, followed by
alphanumeric characters, and be at least 6 characters long.");
returnfalse;
}

if (!mobilePattern.test(mobile)) {
alert("Invalid Mobile Number: Must contain exactly 10
digits.");
returnfalse;
}

if (!emailPattern.test(email)) {
alert("Invalid Email: Must follow the format
example@domain.com");
returnfalse;
}

alert("Form submitted successfully!");


returntrue;
}
</script>
</head>
<body>
<h2>Registration Form</h2>
<formonsubmit="return validateForm()">
<labelfor="name">Name:</label>
<inputtype="text"id="name"name="name"required><br><br>

<labelfor="mobile">Mobile:</label>
<inputtype="text"id="mobile"name="mobile"required><br><br>

<labelfor="email">Email:</label>
<inputtype="text"id="email"name="email"required><br><br>

<inputtype="submit"value="Register">
</form>
</body>
</html>

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