In this article, we will learn how we can add two numbers using call by reference approach.
The program takes two integer inputs from the user and prints their sum as a result.
Sample Input:
Enter the first number: 10
Enter the second number: 20
Output:
The sum of the two numbers is: 30
Before diving into the detailed explanation of the program, let’s first understand what is call by reference approach in C programming.
In C programming, you can pass parameters to a function in two ways. First, pass by value, and second pass by reference.
When we use the pass by value approach, we directly pass the value of the variable to a function as a parameter.
Whereas, when we use the pass by reference approach, we rather pass the memory address of the variable to a function as a parameter. It means if you make any changes to the parameter inside the called function, it will directly affect the value of the original variable.
The following program shows how you can add two numbers using call by reference approach:
// C program to add two numbers // using call by reference approach #include <stdio.h> // Get references of a & b and return the sum int add(int *ptr1, int *ptr2){ int res; // Get the sum res = *ptr1 + *ptr2; return res; } int main(){ // Declare the variables int a, b, result; // Get the first number printf("Enter the first number: "); scanf("%d", &a); // Get the second number printf("Enter the second number: "); scanf("%d", &b); // Pass a & b parameters by their reference result = add(&a, &b); // Print the result printf("The sum of the two numbers is: %d", result); return 0; }
Output:
Enter the first number: 10 Enter the second number: 20 The sum of the two numbers is: 30
Code Explanation:
- We have declared two variables
a
&b
to get the two numbers from the user as input and a variableresult
to store the result of the addition. - To pass the variables
a
&b
by reference to theadd()
function, we placed an ampersand(&
) symbol before each variable. This will pass their memory address to the add() function instead of their values. - To handle the references(memory addresses) of variables
a
andb
, we declared two pointer variablesint *ptr1
andint *ptr2
as add() function parameters. - Now, to get the sum we have to dereference the pointers ptr1 and ptr2, i.e.
*ptr1 + *ptr2
. Please note that ptr1 and ptr2 give the memory addresses ofa
andb
whereas *ptr1 and *ptr2 give the values stored in a and b. - Finally, return the sum of the two numbers from the add() function.
- The returned sum is stored in the
result
variable. Print it using the printf() function.
Thanks for reading.