2.
1 Program to Calculate Arithmetic Operations using Function
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
float divide(int a, int b) {
return (float)a / b;
}
int main() {
int x = 20, y = 10;
cout << "Addition = " << add(x, y) << endl;
cout << "Subtraction = " << subtract(x, y) << endl;
cout << "Multiplication = " << multiply(x, y) << endl;
cout << "Division = " << divide(x, y) << endl;
return 0;
}
Output:
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
2.2 Program for Implementing Call by Value
#include <iostream>
using namespace std;
void swapValue(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "Inside function: a = " << a << ", b = " << b << endl;
}
int main() {
int x = 5, y = 10;
cout << "Before function call: x = " << x << ", y = " << y << endl;
swapValue(x, y);
cout << "After function call: x = " << x << ", y = " << y << endl;
return 0;
}
Output:
Before function call: x = 5, y = 10
Inside function: a = 10, b = 5
After function call: x = 5, y = 10
2.3 Program for Implementing Call by Reference
#include <iostream>
using namespace std;
void swapReference(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swapReference(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
Output:
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
2.4 Program for Implementing Function Overloading (Area of
Shapes)
#include <iostream>
using namespace std;
int area(int side) {
return side * side;
}
int area(int l, int b) {
return l * b;
}
float area(float r) {
return 3.14f * r * r;
}
int main() {
cout << "Area of square (side=5): " << area(5) << endl;
cout << "Area of rectangle (l=4, b=6): " << area(4, 6) << endl;
cout << "Area of circle (r=3): " << area(3.0f) << endl;
return 0;
}
Output:
Area of square (side=5): 25
Area of rectangle (l=4, b=6): 24
Area of circle (r=3): 28.26
2.5 Program for Implementing Inline Function
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << "Square of 5 = " << square(5) << endl;
cout << "Square of 10 = " << square(10) << endl;
return 0;
}
Output:
Square of 5 = 25
Square of 10 = 100