Parameter passing methods and Recursion function


Parameter passing methods:
In ‘C’ language there are two ways that the parameters can be passed to a function, they are
i).  Call by value
ii). Call by reference
1.  Call by value:
  • This method copies the values of actual parameters into the formal parameters of the function.
  • Here, the changes in the formal parameters cannot affect the actual parameters, because formal arguments are a photocopy of actual arguments.
Note: If no idea about actual and formal arguments means the below link to use for learning this topic.
Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int n=2;
clrscr();
printf("The %d of cubic value is %d",n,cube_func(n));//function calling
getch();
}
//function definition
int cube_func(int x)
{
x=x*x*x;
return(x);
}

Output:
2. Call by reference:
  • It is another way of passing parameters to the function.
  • Here, the address of arguments is copied into the parameters inside the function, the address is used to access the actual arguments used in the call.
  • Hence changes made in the arguments are permanent.
  • Here pointers are passed to function, just like any other arguments and we need not declare the parameters as a pointer type.
Example: Interchanging two values.

#include<stdio.h>
#include<conio.h>
void interchange_func(int *x,int *y);//function declaration with pointer
void main()
{
int a=5,b=7;
clrscr();
printf("\n a and b values before interchanging : %d %d\n",a,b);
interchange_func(&a,&b);//pass address to the function
printf(" a and b values after interchanging : %d %d\n",a,b);
getch();
}
//function definition
void interchange_func(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}

Output:
Recursion:
  • It is the process being performed where one of the instructions is to “repeat the process”.
  • This makes it sound very similar to a loop because it repeats the same code, and in some ways, it is similar to looping.
  • It is the process of calling the same function itself again and again until some condition is satisfied. This process is used for repetitive computation in which each action is satisfied in terms of a previous result.
Syntax:

Function1()
{
          Function1();
}

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("\n Enter the number: ");
scanf("%d",&a);
printf("\n The factorial of %d=%d",a,recursive_func(a));// function call
getch();
}
recursive_func(int x)// function declaration
{
int f;
if(x==1)
          return(1);
else
          f=x*recursive_func(x-1);// recursive function
          return(f);
}

Output:
Share:

No comments:

Post a Comment

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me