Write a CPP program to perform arithmetic operations using inline function.
Introduction
This code demonstrates how to perform basic arithmetic operations in C++. It includes functions for addition, subtraction, multiplication, and division, which are called using inline function definitions.
Key Concepts
- Inline Functions: Functions (add, subtract, multi, divide) are declared with the inline keyword. These functions perform basic arithmetic operations on two float numbers and display the result.
- User Input: The program takes two float numbers as input from the user.
- Function Calls: The program calls the inline functions (add, subtract, multi, divide) to perform arithmetic operations on the input numbers.
Code Structure
The code starts with the necessary header file inclusion and the declaration of inline functions for each arithmetic operation. It then defines the main function, where the user is prompted to enter two values. The code calls the inline functions for each arithmetic operation and displays the results.
Code Examples
C++
#include<iostream> using namespace std; inline void add(float a,float b) //inline function definition
{ float c = a + b; cout<<a<<" + "<<b<<" = "<<c<<endl; }
inline void subtract(float a,float b) //inline function definition
{ float c = a - b; cout<<a<<" - "<<b<<" = "<<c<<endl;
}
inline void multi(float a,float b) //inline function definition { float c = a * b; cout<<a<<" * "<<b<<" = "<<c<<endl; }
inline void divide(float a,float b) //inline function definition { float c = a / b; cout<<a<<" / "<<b<<" = "<<c<<endl; }
int main() { float n1,n2; cout<<"Enter two values to perform arithmetic operations : "; cin>>n1>>n2; cout<<endl; add(n1,n2); subtract(n1,n2); multi(n1,n2); divide(n1,n2); //inline function calling return 0; }
Explanation
- User Input: The program prompts the user to input two float numbers (n1 and n2).
- Inline Functions: Four inline functions (add, subtract, multi, divide) are defined to perform basic arithmetic operations on the input numbers.
- Function Calls: The program calls these inline functions, passing the user-input numbers, to perform addition, subtraction, multiplication, and division.
Conclusion
This C++ program showcases the use of inline functions to perform basic arithmetic operations. Inline functions are suitable for small, frequently called functions, as they help reduce the function call overhead. The program takes user input, performs arithmetic operations using inline functions, and displays the results.