0% found this document useful (0 votes)
8 views18 pages

Final Suggestions

The document provides multiple programming tasks and solutions, including creating a web page for summing two float numbers, showcasing JavaScript event listeners, and implementing PHP functions for array manipulation and object-oriented programming. It covers various topics such as HTML, JavaScript, PHP, and MySQL database interactions. Each section includes code examples and explanations for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Final Suggestions

The document provides multiple programming tasks and solutions, including creating a web page for summing two float numbers, showcasing JavaScript event listeners, and implementing PHP functions for array manipulation and object-oriented programming. It covers various topics such as HTML, JavaScript, PHP, and MySQL database interactions. Each section includes code examples and explanations for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Suggestion

1. Question-1
Create a web page that allows the user to enter two float numbers and calculates
their sum when a "Sum" button is clicked.
Requirements:
1. Create two input fields to accept float numbers.
2. Add a button labeled "Sum".
3. When the button is clicked:
o Read the values from the input fields.

o Convert them to float numbers.

o Calculate their sum.

o Display the result on the page.

Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sum of Two Numbers</title>
</head>
<body>
<h2>Sum Two Numbers</h2>

<label>First Number:</label><br>
<input type="text" id="num1" placeholder="Enter first number"><br><br>

<label>Second Number:</label><br>
<input type="text" id="num2" placeholder="Enter second number"><br><br>

<button id="sumBtn">Sum</button>

<p>Result: <span id="result">0</span></p>

<script>
Page 1 of 18
// Select elements
const num1Input = document.getElementById("num1");
const num2Input = document.getElementById("num2");
const sumBtn = document.getElementById("sumBtn");
const resultSpan = document.getElementById("result");

// Add click event listener


sumBtn.addEventListener("click", function() {
// Convert input values to float
const num1 = parseFloat(num1Input.value);
const num2 = parseFloat(num2Input.value);

// Check if inputs are valid numbers


if (isNaN(num1) || isNaN(num2)) {
resultSpan.textContent = "Please enter valid numbers!";
return;
}

// Calculate sum
const sum = num1 + num2;

// Display result
resultSpan.textContent = sum;
});
</script>
</body>
</html>

Page 2 of 18
2. Question:
Showcase different types of event listeners by creating a JavaScript program that
includes suitable examples, and explain how each listener works as well as how it
reacts to user interactions.

a) Answer:
 click
 mouseover / mouseout
 dblclick
 keydown / keyup
 change
 submit

b) How Each Event Works


Event Trigger Example in Code Response
click User clicks on an clickBtn.addEventListener('click', ...) Displays "Button was
element clicked!"
mouseover Mouse pointer hoverBox.addEventListener('mouseover', Changes box color and
enters an ...) shows message
element
mouseout Mouse pointer hoverBox.addEventListener('mouseout', .. Resets color and
leaves an .) updates message
element
dblclick User double- dblClickBtn.addEventListener('dblclick', ... Shows "Button was
clicks an element ) double-clicked!"
keydown Key is pressed keyInput.addEventListener('keydown', ...) Displays the pressed
down key name
keyup Key is released keyInput.addEventListener('keyup', ...) Displays the released
key name
change Value of an input dropdown.addEventListener('change', ...) Shows selected option
or select changes
submit Form submission myForm.addEventListener('submit', ...) Displays "Form was
attempt submitted!" without
reloading

c) Example:
<!DOCTYPE html>
Page 3 of 18
<html>
<head>
<title>Event Listener Examples</title>
<style>
#hoverBox {
width: 150px;
height: 100px;
background-color: lightblue;
text-align: center;
line-height: 100px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h2>JavaScript Event Listeners Demo</h2>

<!-- Click Event -->


<button id="clickBtn">Click Me</button>

<!-- Mouseover / Mouseout -->


<div id="hoverBox">Hover over me</div>

<!-- Double Click -->


<button id="dblClickBtn">Double Click Me</button>

<!-- Keydown / Keyup -->


<input type="text" id="keyInput" placeholder="Type something">

<!-- Change Event -->


<select id="dropdown">
<option value="">Select an option</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="Java">Java</option>
</select>

<!-- Submit Event -->


Page 4 of 18
<form id="myForm">
<input type="text" placeholder="Enter name">
<button type="submit">Submit</button>
</form>

<p id="output"></p>

<script>
const output = document.getElementById('output');

// 1. Click Event
document.getElementById('clickBtn').addEventListener('click', function() {
output.textContent = 'Button was clicked!';
});

// 2. Mouseover / Mouseout Events


const hoverBox = document.getElementById('hoverBox');
hoverBox.addEventListener('mouseover', function() {
hoverBox.style.backgroundColor = 'lightgreen';
output.textContent = 'Mouse entered the box!';
});
hoverBox.addEventListener('mouseout', function() {
hoverBox.style.backgroundColor = 'lightblue';
output.textContent = 'Mouse left the box!';
});

// 3. Double Click Event


document.getElementById('dblClickBtn').addEventListener('dblclick', function() {
output.textContent = 'Button was double-clicked!';
});

// 4. Keydown / Keyup Events


document.getElementById('keyInput').addEventListener('keydown', function(event) {
output.textContent = `Key down: ${event.key}`;
});
document.getElementById('keyInput').addEventListener('keyup', function(event) {
output.textContent = `Key up: ${event.key}`;
});
Page 5 of 18
// 5. Change Event
document.getElementById('dropdown').addEventListener('change', function() {
output.textContent = `You selected: ${this.value}`;
});

// 6. Submit Event
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page reload
output.textContent = 'Form was submitted!';
});
</script>
</body>
</html>

Page 6 of 18
3. Question-2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Click Event</title>
</head>
<body>
<button class="btn">First Button</button>
<img id="myImage" src="image1.jpg" alt="Click me" width="200">
<p>Click Count: <span id="count">0</span></p>
<script> // JavaScript code will go here </script>
</body>
</html>

Create a JavaScript function that adds a click event listener to the image with the ID myImage. On
each click:
i. Change the image source from "image1.jpg" to "image2.jpg".
ii. Increase the numeric value displayed in the #count span by 1.

a) Anwer:
<script>
// Get elements
const image = document.getElementById("myImage");
const countSpan = document.getElementById("count");

// Attach click event listener to image


image.addEventListener("click", function () {
// 1. Change image source
image.src = "image2.jpg";

// 2. Increment click count


let currentCount = parseInt(countSpan.textContent);
countSpan.textContent = currentCount + 1;
});
</script>

Page 7 of 18
b) How it works
1. Selecting elements
o document.getElementById("myImage") gets the image.
o document.getElementById("count") gets the span that displays the number.
2. Adding the event listener
o .addEventListener("click", function(){...}) makes the image react to clicks.
3. Changing the image source
o image.src = "image2.jpg"; swaps the image file.
4. Incrementing the counter
o parseInt(countSpan.textContent) converts the span text to a number.
o currentCount + 1 increases the value.
o Updated count is shown by countSpan.textContent = ....

Page 8 of 18
4. Question-3
Write a PHP program that takes two arrays of numbers, identifies the smallest number in the first
array and the largest number in the second array, then calculates and returns the average of these
two values.

<?php
function averageOfExtremes($arrX, $arrY) {
// Solution code will go here
}
// Example Usage
$arrX = [8, 3, 2, 1, 5];
$arrY = [9, 5, 1, 4, 2];
echo averageOfExtremes($arrX, $ arrY); // Output: 6
?>
Prepare the solution code by using PHP.

a) Answer:
<?php
function averageOfExtremes($arrX, $arrY) {
// Find smallest number in first array
$minValue = min($arrX);

// Find largest number in second array


$maxValue = max($arrY);

// Calculate average
$average = ($minValue + $maxValue) / 2;

return $average;
}

// Example Usage
$arrX = [8, 3, 2, 1, 5];
$arrY = [9, 5, 1, 4, 2];
echo averageOfExtremes($arrX, $arrY); // Output: 6
?>

Page 9 of 18
5. Question-4
Create a PHP OOP program to model a number addition system using an interface and
a trait:
i. Define an Input interface with a method setNumbers($a, $b) to assign two numbers.
ii. Define a Logger trait containing a method log($message) to display messages.
iii. Implement a class Addition that uses the Logger trait and implements the Input
interface. The class should compute the sum of the two numbers. Instantiate the class,
assign two numbers, perform the addition, and output the result along with log
messages.

a) Answer:
<?php
// 1. Define the Input interface
interface Input {
public function setNumbers($a, $b);
}

// 2. Define the Logger trait


trait Logger {
public function log($message) {
echo "[LOG]: " . $message . "<br>";
}
}

// 3. Implement the Addition class


class Addition implements Input {
use Logger; // Use the Logger trait

private $num1;
private $num2;

// Implement the setNumbers method from Input interface


public function setNumbers($a, $b) {
$this->num1 = $a;
$this->num2 = $b;
$this->log("Numbers set to $a and $b");
Page 10 of 18
}

// Method to compute the sum


public function computeSum() {
$sum = $this->num1 + $this->num2;
$this->log("Computed sum: $sum");
return $sum;
}
}

// 4. Example usage
$addition = new Addition();

// Assign two numbers


$addition->setNumbers(10, 20);

// Perform addition and display result


$result = $addition->computeSum();
echo "The sum of the numbers is: $result";
?>

Page 11 of 18
6. Question-5
Route::get('/product', [ProductController::class, 'index'])->name('product.index');
 Role: Defines the URL /product and maps it to the index method of the

ProductController.
 Responsibility: Determines which controller and method should handle the

incoming GET request from the browser.


 Additional Function: Assigns a route name (product.index) for easy reference

elsewhere in the application.


2. Controller (ProductController)
public function index()
{
$products = Product::all();
return view('products.index', compact('products'));
}

Answer:
a) Responsibilities:
1. URL Mapping – Maps the HTTP GET request to the URL /product to a specific
controller method (ProductController@index).
2. Controller Delegation – Passes the request to the controller so business logic is
handled outside the route.
3. Named Route – name('product.index') allows you to refer to this route by name in
views or redirects, e.g., route('product.index').
Key Role: Acts as the entry point for the HTTP request.

b) Controller (ProductController) Responsibilities:


1. Business Logic – Decides what data to retrieve and how to process it.
2. Data Retrieval – Uses the Product model to fetch all records from the database
(Product::all()).
3. View Rendering – Passes data to the view using view('products.index',
compact('products')).
Key Role: Acts as a mediator between the Model and the View, handling application
logic.
Page 12 of 18
c) Model (Product)
 Located at app/Models/Product.php.
Responsibilities:
1. Database Interaction – Represents the products table and allows you to query it.
2. Eloquent ORM – Provides methods like all(), find(), create(), etc., for database
operations.
3. Data Representation – Each Product object represents a row in the database table.
Key Role: Encapsulates data access and represents the business entity.

d) View (resources/views/products/index.blade.php)
Responsibilities:
1. Presentation Layer – Displays the data to the user.
2. Receives Data – Gets the $products variable passed from the controller.
3. HTML & Blade Logic – Uses Blade templating to loop through products, format,
and display them.
Key Role: Responsible for user interface and rendering the content to the browser.

e) Flow of Request
1. User visits /product.
2. Route matches the URL and calls ProductController@index.
3. Controller fetches all products using the Model.
4. Controller passes data to the View.
5. View renders HTML and sends it back to the user.

Page 13 of 18
7. Question-6
In a Student Management System, the administrator must be able to handle student
records. Develop a PHP-MySQL application to add new students with the following
requirements:
 Connect to the MySQL database.
 Create a PHP form to input the student’s name, roll number, and department.
 Insert the student information into the database when the form is submitted.
 Show a confirmation message after the record has been successfully added.

a) Create MySQL Database & Table


CREATE DATABASE student_management;
-- Use the database
USE student_management;

-- Create students table


CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
roll_number VARCHAR(20) NOT NULL,
department VARCHAR(50) NOT NULL
);

b) Database Connection (db.php)


<?php
$host = "localhost";
$user = "root"; // your DB username
$password = ""; // your DB password
$database = "student_management";

// Create connection
$conn = new mysqli($host, $user, $password, $database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Page 14 of 18
?>
c) PHP Form to Add Student (add_student.php)
<?php
include 'db.php'; // include database connection

$message = "";

if (isset($_POST['submit'])) {
// Get form data
$name = $_POST['name'];
$roll = $_POST['roll_number'];
$department = $_POST['department'];

// Insert into database


$sql = "INSERT INTO students (name, roll_number, department) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $name, $roll, $department);

if ($stmt->execute()) {
$message = "Student record added successfully!";
} else {
$message = "Error: " . $stmt->error;
}

$stmt->close();
}
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Student</title>
</head>
<body>
<h2>Add New Student</h2>

Page 15 of 18
<?php if($message != "") { echo "<p>$message</p>"; } ?>

<form method="POST" action="">


<label>Name:</label><br>
<input type="text" name="name" required><br><br>

<label>Roll Number:</label><br>
<input type="text" name="roll_number" required><br><br>

<label>Department:</label><br>
<input type="text" name="department" required><br><br>

<input type="submit" name="submit" value="Add Student">


</form>
</body>
</html>

Page 16 of 18
8. Question –8
Create a Bootstrap-styled contact form that allows a user to submit their name, email,
and message.
Requirements:
1. Use Bootstrap classes for styling the form elements:
o Inputs should use form-control.

o Submit button should use btn and btn-success.

o The form should be inside a Bootstrap card with padding and a shadow.

2. Form fields:
o Name (text input)

o Email (email input)

o Message (textarea)

3. When the user clicks the Submit button:


o Validate that all fields are filled.

o If any field is empty, show a Bootstrap alert-danger message.

o If all fields are filled, show a Bootstrap alert-success message with:

"Thank you, [Name]! Your message has been submitted."

Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bootstrap Contact Form</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<div class="card shadow p-4">
<h2 class="mb-4">Contact Us</h2>

<!-- Contact Form -->


<form action="submit_form.php" method="POST" class="needs-validation" novalidate>
Page 17 of 18
<div class="mb-3">
<label for="name" class="form-label">Name:</label>
<input type="text" class="form-control" id="name" name="name" required>
<div class="invalid-feedback">
Please enter your name.
</div>
</div>

<div class="mb-3">
<label for="email" class="form-label">Email:</label>
<input type="email" class="form-control" id="email" name="email" required>
<div class="invalid-feedback">
Please enter a valid email.
</div>
</div>

<div class="mb-3">
<label for="message" class="form-label">Message:</label>
<textarea class="form-control" id="message" name="message" rows="4" required></textarea>
<div class="invalid-feedback">
Please enter your message.
</div>
</div>

<button type="submit" class="btn btn-success">Submit</button>


</form>
</div>
</div>

<!-- Bootstrap JS (for validation styling) -->


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>

Page 18 of 18

You might also like