Batch files are a great way to automate tasks in Windows using simple scripting. If you’re just starting to learn how batch files work, creating a script to add two numbers is a perfect beginner project.
In this article, you’ll learn how to write and run a batch file that takes two numbers from the user, adds them, and displays the result.
📄 What is a Batch File?
A batch file is a plain text file containing a series of commands that are executed in sequence by the Windows Command Prompt (CMD). Batch files use the .bat
extension and are commonly used for automating tasks.
🛠 Steps to Create a Batch File to Add Two Numbers
1. Open Notepad
Start by opening Notepad or any plain text editor.
2. Copy and Paste the Following Code:
@echo off
setlocal
:: Ask for first number
set /p num1=Enter the first number:
:: Ask for second number
set /p num2=Enter the second number:
:: Add the two numbers
set /a sum=%num1% + %num2%
:: Display the result
echo The sum of %num1% and %num2% is %sum%.
pause
endlocal
3. Save the File
- Go to File > Save As.
- Name the file something like:
add_numbers.bat
. - Change Save as type to All Files.
- Click Save.
4. Run the Batch File
Double-click the add_numbers.bat
file. A Command Prompt window will open, asking you to input two numbers. After entering both numbers, the script will display their sum.
✅ Sample Output
Enter the first number: 10
Enter the second number: 25
The sum of 10 and 25 is 35.
📌 Important Notes
- The
set /a
command is used to perform arithmetic operations. - This script only works with whole numbers (integers).
- If you want to work with decimal numbers, you’ll need to use PowerShell or another scripting language like Python.
🧠 Use Case
This simple script can be a great learning tool for:
- Students learning programming basics
- System administrators writing small utility tools
- Automating basic numeric tasks via batch scripting
🧾 Conclusion
Creating a batch file to add two numbers is an excellent way to understand user input, variables, and basic arithmetic in batch scripting. While limited to integers, it’s a helpful building block for more advanced automation scripts.
Let me know if you want to expand this into a calculator that supports subtraction, multiplication, and division as well!