Introduction
Dividing two numbers is a basic arithmetic operation. In JavaScript, you can easily divide two numbers using the /
operator. This guide will walk you through writing a JavaScript program to divide two numbers.
Problem Statement
Create a JavaScript program that:
- Accepts two numbers.
- Divides the first number by the second number.
- Returns the result.
Example:
Input:
10
and2
Output:
5
Input:
15
and3
Output:
5
Solution Steps
- Read the Input Numbers: Provide two numbers either by user input or directly in the code.
- Divide the Numbers: Use the
/
operator to divide the first number by the second. - Handle Division by Zero: Ensure that the divisor is not zero to avoid errors.
- Display the Result: Print the result of the division.
JavaScript Program
// JavaScript Program to Divide Two Numbers
// Author: https://www.javaguides.net/
function divideTwoNumbers(num1, num2) {
// Step 1: Handle division by zero
if (num2 === 0) {
console.log("Error: Division by zero is not allowed.");
return;
}
// Step 2: Divide the two numbers
const result = num1 / num2;
// Step 3: Display the result
console.log(`The result of dividing ${num1} by ${num2} is: ${result}`);
}
// Example input
let number1 = 10;
let number2 = 2;
divideTwoNumbers(number1, number2);
Explanation
Step 1: Handle Division by Zero
- Before performing the division, the function checks if the divisor (
num2
) is zero. If it is, an error message is displayed to prevent a division by zero error.
Step 2: Divide the Two Numbers
- The numbers
number1
andnumber2
are passed as arguments to thedivideTwoNumbers()
function. The division is performed using the/
operator.
Step 3: Display the Result
- The result of the division is stored in the variable
result
and displayed usingconsole.log()
.
Output Example
The result of dividing 10 by 2 is: 5
Example with Different Input
If you modify the input to:
let number1 = 15;
let number2 = 3;
The output will be:
The result of dividing 15 by 3 is: 5
Division by Zero Example
let number1 = 10;
let number2 = 0;
The output will be:
Error: Division by zero is not allowed.
Conclusion
This JavaScript program demonstrates how to divide two numbers using the /
operator while ensuring that the divisor is not zero. Handling division by zero is important to avoid runtime errors. This simple arithmetic operation is widely used in various programming tasks, and the program provides a straightforward solution for performing division in JavaScript.
Comments
Post a Comment
Leave Comment