Introduction
In this lab, you will learn how to write a C++ program to perform arithmetic operations using functions. Specifically, you will create separate functions for addition, subtraction, multiplication, and division of two numbers, inputted by the user.
Create a new C++ file
Create a new file named main.cpp in the ~/project directory.
touch ~/project/main.cpp
Include necessary libraries
Include the iostream library, as shown below:
#include<iostream>
using namespace std;
Define user-defined functions
Define individual functions to perform arithmetic operations using the two numbers entered by the user. Define four separate functions to perform addition, subtraction, multiplication, and division, as shown below:
int sum(int a,int b)
{
rem=a+b;
return(rem);
}
int sub(int a,int b)
{
rem=a-b;
return(rem);
}
int mul(int a,int b)
{
rem=a*b;
return(rem);
}
int div(int a,int b)
{
rem=a/b;
return(rem);
}
In each function, a and b represent the two inputted integers. The functions return the value of the result of the arithmetic operation performed.
Input two numbers
Prompt the user to enter two integer values, as shown below:
int main()
{
int a,b,m,su,s,d;
cout<<"Enter Two Numbers : \n";
cin>>a>>b;
Perform arithmetic operations using user-defined functions
Call each of the four function and pass the two inputted integer values as parameters, as shown below:
s=sum(a,b);
su=sub(a,b);
m=mul(a,b);
d=div(a,b);
Output results of arithmetic operations
Output the results of the arithmetic operations performed, as shown below:
cout<<"\nSum : = "<<s<<"\nSubtraction : = "<<su<<endl;
cout<<"\nMultiplication : = "<<m<<"\n Division : = "<<d<<endl;
Compile and run the code
Use the following command to compile and run the code:
g++ main.cpp -o main && ./main
Review the full code of the main.cpp file
#include<iostream>
using namespace std;
int sum(int,int);
int sub(int,int);
int mul(int,int);
int div(int,int);
int rem;
int main()
{
int a,b,m,su,s,d;
cout<<"Enter Two Numbers : \n";
cin>>a>>b;
s=sum(a,b);
su=sub(a,b);
m=mul(a,b);
d=div(a,b);
cout<<"\nSum : = "<<s<<"\nSubtraction : = "<<su<<endl;
cout<<"\nMultiplication : = "<<m<<"\n Division : = "<<d<<endl;
return 0;
}
int sum(int a,int b)
{
rem=a+b;
return(rem);
}
int sub(int a,int b)
{
rem=a-b;
return(rem);
}
int mul(int a,int b)
{
rem=a*b;
return(rem);
}
int div(int a,int b)
{
rem=a/b;
return(rem);
}
Summary
In this lab, you learned how to create a C++ program that performs arithmetic operations using functions. You wrote separate functions for performing arithmetic operations such as addition, subtraction, multiplication, and division, of two integer values inputted by the user. You then compiled and ran the code to see the results of the arithmetic operations performed, outputting them to the console.



