📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Subtracting two numbers is a basic arithmetic operation commonly used in programming. In JavaScript, you can easily perform subtraction using the -
operator. This guide will walk you through writing a JavaScript program to subtract two numbers.
Problem Statement
Create a JavaScript program that:
- Accepts two numbers.
- Subtracts the second number from the first number.
- Returns the result of the subtraction.
Example:
Input:
15
and5
Output:
10
Input:
7
and3
Output:
4
Solution Steps
- Read the Input Numbers: Provide two numbers either as part of user input or directly in the code.
- Subtract the Numbers: Use the
-
operator to subtract the second number from the first. - Display the Result: Print the result of the subtraction.
JavaScript Program
// JavaScript Program to Subtract Two Numbers // Author: https://www.javaguides.net/ function subtractTwoNumbers(num1, num2) { // Step 1: Subtract the second number from the first const difference = num1 - num2; // Step 2: Display the result console.log(`The difference between ${num1} and ${num2} is: ${difference}`); } // Example input let number1 = 15; let number2 = 5; subtractTwoNumbers(number1, number2);
Output Example
The difference between 15 and 5 is: 10
Example with Different Input
If you modify the input to:
let number1 = 7; let number2 = 3;
The output will be:
The difference between 7 and 3 is: 4
Explanation
Step 1: Subtract the Two Numbers
- The numbers are passed as arguments to the
subtractTwoNumbers()
function, where they are subtracted using the-
operator.
Step 2: Display the Result
- The result of the subtraction is stored in the variable
difference
and displayed usingconsole.log()
.
Conclusion
This JavaScript program demonstrates how to subtract two numbers using the -
operator. This basic arithmetic operation is essential in many programming tasks, and the program serves as a foundation for learning how to perform mathematical operations in JavaScript.
Comments
Post a Comment
Leave Comment