Computer ScienceNEB 2082

Write JavaScript code to input any three numbers and find the smallest number among them. [5] OR Write a PHP script to connect to a MySQL database. [5]

5

Answer

JavaScript Solution (Finding the Smallest of Three Numbers)

// JavaScript code to input three numbers and find the smallest
let num1 = parseFloat(prompt("Enter first number:"));
let num2 = parseFloat(prompt("Enter second number:"));
let num3 = parseFloat(prompt("Enter third number:"));

// Check which number is smallest
if (num1 <= num2 && num1 <= num3) {
    smallest = num1;
} else if (num2 <= num1 && num2 <= num3) {
    smallest = num2;
} else {
    smallest = num3;
}

// Display the result
document.write("The smallest number among " + num1 + ", " + num2 + ", and " + num3 + " is: <b>" + smallest + "</b>");

How it works:

  1. The script uses prompt() to take three numeric inputs from the user.
  2. It converts the inputs to floating-point numbers using parseFloat() to handle decimal values.
  3. Three if-else conditions compare the numbers to determine the smallest:
    • First checks if num1 is the smallest.
    • If not, checks if num2 is the smallest.
    • If neither is smallest, num3 must be the smallest.
  4. The result is displayed using document.write() with the smallest number highlighted in bold.

PHP Solution (Connecting to MySQL Database)

<?php
// PHP script to connect to MySQL database
$servername = "localhost";  // Replace with your server if different
$username = "root";         // Replace with your MySQL username
$password = "";             // Replace with your MySQL password
$dbname = "test_db";        // Replace with your database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo "<p style='color:green;'>Connected successfully to MySQL database!</p>";
}

// Close connection
$conn->close();
?>

How it works:

  1. The script defines four variables:
    • $servername: Hostname (default: localhost).
    • $username and $password: MySQL credentials (replace with actual values).
    • $dbname: Name of the database to connect to.
  2. It creates a connection using new mysqli().
  3. The if-else block checks if the connection succeeded:
    • If connect_error exists, it displays the error message.
    • If successful, it prints a green success message.
  4. The connection is closed using $conn->close() to free resources.

Discussion

Loading…

More Computer Science questions

All Computer Science old questions