A function may or may not return a value. A ‘return’ statement returns some value to the calling function and it may be assigned to the variable in the left side of the calling function. The return value can be a constant, variable, a user defined data structure, a general expression, a pointer to function, or a function call. The return statement also causes the program logic to return to the point from which the function was accessed. In general term the return statement is written as
return expression;
If a function does not return a value, the return type
in the function definition and declaration is specified as void. The declaration
for a prototype for a function that receive any arguments from the calling
function and does not return any value will have the formatvoid function_name (void);
The above program can be rewrite as
#include <stdio.h>
#include <conio.h>
int add(int p,int q); // function prototype
void display(int p, int q, int r); // function prototype
int main()
{
int a,b,c;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
display(a,b,c);
getch();
return 0;
}
int add(int p,int q) //This function returns sum of a and b.
{
return(p+q);
}
void display(int p, int q, int r). //This function returns nothing
{
printf("Sum of %d and %d is %d",p,q,r);
}
#include <conio.h>
int add(int p,int q); // function prototype
void display(int p, int q, int r); // function prototype
int main()
{
int a,b,c;
clrscr();
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
display(a,b,c);
getch();
return 0;
}
int add(int p,int q) //This function returns sum of a and b.
{
return(p+q);
}
void display(int p, int q, int r). //This function returns nothing
{
printf("Sum of %d and %d is %d",p,q,r);
}
Pass by value
Arguments can be passed to a function by two methods, They are- pass by value
- pass by reference
Example:
Pass by Reference
When passing by reference technique is used, the address of the data item is passed to the called function. Using & operator we can determine the address of the data item. Note that function once receives a data item by reference, it acts on data item and the changes made to the data item also reflects on the calling function. Here you don't need to return anything to calling function.Example:
Recursion
Recursive functions are those functions, which call itself within that function. A recursive function must have the following type of statements.-
A statement to test and determine whether the function is calling itself
again.
-
A statement that calls the function itself and must be argument.
-
A conditional statement (if-else)
-
A return statement.
This is the most famous program on recursion. Many versions of this program are available. All programs differ only in checking conditions. I prefer to write like the following one.
No comments:
Post a Comment