JavaScript Program to Find the Remainder of Two Numbers

Introduction

Finding the remainder when one number is divided by another is a common operation in programming known as the modulus operation. In JavaScript, this operation is performed using the % operator. This guide will walk you through writing a JavaScript program to find the remainder of two numbers.

Problem Statement

Create a JavaScript program that:

  • Accepts two numbers.
  • Finds the remainder when the first number is divided by the second number.
  • Returns the result.

Example:

  • Input: 10 and 3

  • Output: 1

  • Input: 25 and 4

  • Output: 1

Solution Steps

  1. Read the Input Numbers: Provide two numbers either by user input or directly in the code.
  2. Calculate the Remainder: Use the % operator to find the remainder of the two numbers.
  3. Handle Division by Zero: Ensure the divisor is not zero to avoid errors.
  4. Display the Result: Print the remainder.

JavaScript Program

// JavaScript Program to Find the Remainder of Two Numbers
// Author: https://www.javaguides.net/

function findRemainder(num1, num2) {
    // Step 1: Handle division by zero
    if (num2 === 0) {
        console.log("Error: Division by zero is not allowed.");
        return;
    }

    // Step 2: Calculate the remainder
    const remainder = num1 % num2;
    
    // Step 3: Display the result
    console.log(`The remainder when ${num1} is divided by ${num2} is: ${remainder}`);
}

// Example input
let number1 = 10;
let number2 = 3;
findRemainder(number1, number2);

Output Example

The remainder when 10 is divided by 3 is: 1

Example with Different Input

If you modify the input to:

let number1 = 25;
let number2 = 4;

The output will be:

The remainder when 25 is divided by 4 is: 1

Division by Zero Example

let number1 = 10;
let number2 = 0;

The output will be:

Error: Division by zero is not allowed.

Explanation

Step 1: Handle Division by Zero

  • Before performing the modulus operation, 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: Calculate the Remainder

  • The numbers number1 and number2 are passed as arguments to the findRemainder() function. The remainder is calculated using the % operator.

Step 3: Display the Result

  • The remainder is stored in the variable remainder and displayed using console.log().

Conclusion

This JavaScript program demonstrates how to find the remainder of two numbers using the % operator. Handling division by zero ensures that the program runs without errors. The modulus operation is widely used in many programming scenarios, and this simple program provides a clear way to perform it in JavaScript.

Comments