You are on page 1of 2

Q)Wht are the different types of function calling?

=>function calling is of two types.


1)call by value
2)call by address/reference
Q)Explain about call by value.
=>While calling a function, if values are supplied as arguments instead of addresses of the variables,
it is known as call by value.
=>when the function call is "call by value", changes made through formal parameters do not get
reflected in actual parameters.
Q)What is the output of the following program?
1 #include<stdio.h>
2 void swap(int,int);
3 main()
4{
5 int n1,n2;
6 n1=10;
7 n2=20;
8 swap(n1,n2);//call by value
9 printf("After swapping n1=%d and n2=%d",n1,n2);
10}
11 void swap(int a,int b)
12 {
13 int c;
14 c=a;
15 a=b;
16 b=c;
17 }

Answer:- After swapping n1=10 and n2=20

Note:- Reason for the unexpected output is, main function is calling swap function as "call by value".
=>when the function call is call by value, changes made through
formal parameters do not get reflected in actual parameters.

Q)Explain about call by reference.


=>While calling a function, if the address of the variable is supplied
as argument it is known as call by reference or call by address.

=>when the function call is call by reference, changes made through


formal parameters get reflected in actual parameters.

Q)Modify the previous program so as to get expected output.

1 #include<stdio.h>
2 void swap(int *,int *);
3 main()
4{
5 int n1,n2;
6 n1=10;
7 n2=20;
8 swap(&n1,&n2);//call by reference
9 printf("After swapping n1=%d and n2=%d",n1,n2);
10}
11void swap(int *a,int *b)
12{
13 int c;
14 c=*a;
15 *a=*b;
16 *b=c;
17 }
Q)What is recursion?
=>A function calling itself is known as recursion.
=>Certain computing problems can be solved efficiently using recursion.
For eg. finding the factorial of a number,finding the Fibonacci series,
traversing a tree(data structure) etc.
=>Programmer has to be careful while implementing recursion.An exit
condition must be defined for the recursive calls of the function.Otherwise,
it will go into an infinite loop.
//factorial.c
1 #include<stdio.h>
2 long int findfactorial(int);
3 main()
4{
5 int n;
6 long int factorial;
7 printf("Enter the number:");
8 scanf("%d",&n);
9 factorial=findfactorial(n);
10 printf("Factorial of %d is %d",n,factorial);
11}
12 long int findfactorial(int i)
13{
14 long int factorial;
15 if(i==0)
16 return 1;
17 else
18 return i*findfactorial(i-1);
19 }

You might also like