Write a simple C++ program to Pass by value and pass by reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> using namespace std; // Function to add two numbers using pass-by-value int addByValue(int a, int b) { return a + b; } // Function to add two numbers using pass-by-reference void addByReference(int &a, int &b, int &result) { result = a + b; } int main() { int num1, num2, result; cout << "Enter the first number: "; cin >> num1; cout << "Enter the second number: "; cin >> num2; // Pass by value int sumValue = addByValue(num1, num2); cout << "Sum using pass-by-value: " << sumValue << endl; // Pass by reference addByReference(num1, num2, result); cout << "Sum using pass-by-reference: " << result << endl; return 0; } |
Output
Enter the first number: 2
Enter the second number: 3
Sum using pass-by-value: 5
Sum using pass-by-reference: 5