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 code to find the smallest number among three inputs
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));
let num3 = parseFloat(prompt("Enter the third number:"));

// Using Math.min() to find the smallest number
let smallest = Math.min(num1, num2, num3);

// Display the result
alert(`The smallest number among ${num1}, ${num2}, and ${num3} is: **${smallest}**`);

// Alternative approach (without Math.min())
/*
let smallest;
if (num1 <= num2 && num1 <= num3) {
    smallest = num1;
} else if (num2 <= num1 && num2 <= num3) {
    smallest = num2;
} else {
    smallest = num3;
}
alert(`The smallest number is: **${smallest}**`);
*/

How it works:

  1. The script prompts the user to input three numbers using prompt() and converts them to floating-point numbers with parseFloat().
  2. The Math.min() function compares the three numbers and returns the smallest value.
  3. The result is displayed using alert() with a formatted string.
  4. The commented alternative shows a manual comparison using if-else logic, which is useful for understanding the underlying logic.

Sample Output: If the user inputs 5, 2, 9, the output will be: The smallest number among 5, 2, and 9 is: **2**.


<?php
// PHP script to connect to a MySQL database

// Database connection parameters
$servername = "localhost";
$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 "Connected successfully to the database!";
}

// Close connection (optional, as PHP automatically closes connections)
$conn->close();
?>

How it works:

  1. The script defines database connection parameters ($servername, $username, $password, $dbname).
  2. It creates a connection to the MySQL database using new mysqli().
  3. The connect_error property checks if the connection failed. If it does, it displays an error message.
  4. If the connection is successful, it prints a success message.
  5. The connection is closed explicitly (though PHP automatically closes it when the script ends).

Sample Output: If the connection is successful, the output will be: Connected successfully to the database!

If the connection fails (e.g., wrong credentials), the output will be: Connection failed: [error message].

Discussion

Loading…

More Computer Science questions

All Computer Science old questions