Pointer: Add two numbers using call by reference
Write a C program to take input of two numbers from user and add that numbers using call by reference method. Let's have a look at the below step by step descriptive logic to add two numbers using call by reference method in C.
Required knowledge-
Pointer: Adding two numbers using call by reference:
1) When we pass address (also known as reference) of variables as an actual arguments while calling a function then this is known as function call by reference.
2) In call by reference, the address of the actual parameters is copied into the formal parameters.
Here is the step by step logic for adding two numbers using call by reference:
- Create a user defined function for adding two numbers using pointer For Example: int addTwoNumbers(long *n1, long *n2)
- Inside the main function, Take input of two numbers 10 and 30 from user and sotre it in some variables like: num1 and num2.
- To add these numbers, you need to call that function by passing reference (Address) of variables like this: addTwoNumbers(&num1, &num2); and then store the value returned by the function in some variable like 'result'.
- At last print the value of 'result' that's it.
/*Program to Add two numbers using call by reference method*/
#include <stdio.h>
int addTwoNumbers(long*, long*);
int main(){
long num1, num2, result;
/*Taking inputs form user*/
printf("Emter two numbers: ");
scanf("%ld %ld", num1, num2);
/*Function call by passing reference*/
result = addTwoNumbers(&num1, &num2);
printf("Sum is %ld", result);
return 0;
}
/*Function definition*/
int addTwoNumbers(long *n1, long *n2){
long sum;
sum = *n1 + *n2;
return sum;
}
When the above code will compile and run the following output will be produced.
Inputs:
Enter two numbers: 10
30
Output:
Sum is 40
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.