FUNCTIONS IN C 2
FUNCTIONS IN C 2
A function may or may not accept any argument. It may or may not return any
value. Based on these facts, There are four different aspects of function calls.
• A function doesn’t pass a arguments but returns a value after completion of the
program.
• A function does pass arguments to function definition but doesn’t return the value.
• A function does pass arguments and return value is known as function arguments
and return type.
• In C, there are various general problems which requires passing more than one
variable of the same type to a function.
• So we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of
values.
• Here, we must notice that we need to pass only the name of the array in the
function which is intended to accept an array. The array defined as the formal
parameter will automatically refer to the array specified by the array name defined
as an actual parameter.
Syntax:
• As we know that, a function can not return more than one value. But in some
problems, we may need to return multiple values from a function.
• In such cases, an array is returned from the function.
• Returning an array is similar to passing the array into the function. The name of
the array is returned from the function.
• Syntax :
int * Function_name() {
//some statements;
return array_type;
}
Ex:
1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12.}
int* Bubble_Sort(int a[]) //array a[] points to arr.
{
int i, j,temp;
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a; }
Recursion in C
• Recursion is the process which comes into existence when a function calls a copy
of itself to work on a smaller problem. Any function which calls itself is called
recursive function, and such function calls are called recursive calls. Recursion
involves several numbers of recursive calls.
Ex:
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}