Call by value and call by reference in C

Write programs to Call by value and call by reference.

Approach 1: Call by Value: In this actual value is passed as arguments in the function

Example: For call by value

Input:  num1 = 10, num2 = 20
Output: Sum is 30

C

#include <stdio.h>

int sumOfTwo(int aint b)
{
    int sum = a + b;
    return sum;
}
int main()
{
    int num1 = 10num2 = 20;

    //call by value to find sum of
    //two numbers
    int sum = sumOfTwo(num1num2);
    printf("Sum is %d"sum);
    return 0;
}

C

Approach 2: Call by Reference: In this arguments are passed by the address.

Example: For call by reference

Input:  num1 = 10, num2 = 20
Output: Numbers befor swapping are num1 = 10, num2 = 20
Numbers after swapping are num1 = 20 , num2 = 10 


#include <stdio.h>

void swap(int *aint *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main()
{
    int num1 = 10num2 = 20;

    printf("Numbers befor swapping are num1 = %d, num2 = %d\n"num1num2);
    //call by reference to swap two
    //numbers
    swap(&num1, &num2);
    printf("Numbers after swapping are num1 = %d , num2 = %d "num1num2);
    return 0;
}


No comments:

Post a Comment