Professional Documents
Culture Documents
Week 10
Week 10
Week 10
Call by Value in C: Calling a function by value will cause the program to copy the contents of an object
passed into a function. To implement this in C, a function declaration has the following form: [return type]
functionName([type] [parameter name],...).
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
int main(){
int x = 20;
int y = 30;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 20, y = 30
Values after swap: x = 20, y = 30
We can observe that even when we change the content of x and y in the scope of the swap function, these
changes do not reflect on x and y variables defined in the scope of main. This is because we call swap() by
value and it will get separate memory for x and y so the changes made in swap() will not reflect in main().
Call by Reference in C: Calling a function by reference will give function parameter the address of original
parameter due to which they will point to same memory location and any changes made in the function
parameter will also reflect in original parameters. To implement this in C, a function declaration has the
following form: [return type] functionName([type]* [parameter name],...).
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
int main(){
int x = 20;
int y = 30;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 20, y = 30
Values after swap: x = 30, y = 20
2. Write a program using the function to display the student details of the class.
3. Write a program to explain nested functions.
The above program's purpose is to determine whether or not the user's input is divisible by 6. An integer is
divisible by 6 if it is also divisible by 2 and 3. First, we created a function called divisionBy2 that accepts an
'int' type parameter as an input. If the condition (x % 2==0) is true, it will return 1, else it will return 0.
Second, a function called 'divisionBy6' is defined, which accepts an "int" type parameter called "y". In this
condition block, if (divisionBy2(y)==1 && y % 3==0), a function call to the 'divisionBy2' function is made.
This 'if' expression, which has two separate parameters, will only return 1 if both arguments are true. If
divisionBy2(y)==1 gives 1, the number is divisible by two, and if y percent 3==0 returns 1, the number is
divisible by three. Because 93 is divisible by three but not by two, it is also not divisible by six.