C++ Program to Subtract Two Numbers Using Functions

In this program, you will learn how to subtract two numbers using functions in the C++ programming language.

This tutorial takes two integers as input, then we define a custom function named Subtract which passes two integers as parameters and returns the result of the subtraction.

Then, this custom function Subtract is called out in the main function to get the result of subtraction of two numbers.

So, without any delay, let’s begin this tutorial.

Contents

C++ Program to Subtract Two Numbers Using Functions

// C++ Program to Subtract Two Numbers Using Functions
#include <iostream>
using namespace std;

int Subtract(int a, int b);

int main(){
    int num1, num2, sub;
    
    // Asking for input
    cout << "Enter the first number: ";
    cin >> num1;
    cout << "Enter the second number: ";
    cin >> num2;
    
    // Calling out function
    sub = Subtract(num1, num2);
    
    // Display output
    cout << "Subtraction of " << num1 << " and " << num2 << " is: " << sub;
    
    return 0;
}

int Subtract(int a, int b){
    return (a - b);
}

Output

Enter the first number: 12
Enter the second number: 5
Subtraction of 12 and 5 is: 7

How Does This Program Work?

    int num1, num2, sub;

We have declared three int data type variables named num1, num2 and sub.

    cout << "Enter the first number: ";
    cin >> num1;
    cout << "Enter the second number: ";
    cin >> num2;

The user is asked to enter two integers. The two integers get stored in the num1 and num2 named variables.

int Subtract(int a, int b){
    return (a - b);
}

We have defined a custom function named Subtract which passes two integers as parameters and returns the result of subtraction.

     sub = Subtract(num1, num2);

After that, we call out the custom function Subtract in the main function.

This gives us the result of the subtraction of two integers num1 and num2. The subtraction of num1 and num2 is stored in the sub named variable.

    cout << "Subtraction of " << num1 << " and " << num2 << " is: " << sub;

At last, we print the result obtained from the above steps using the cout statement.

Conclusion

After going through this tutorial, I hope you understand how to write a C++ program to subtract two numbers using functions.

If you have any doubts regarding the tutorial, comment down your doubts in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *