Functions in C
Functions in C
Defining a function
data- type name( type1 arg1, type2 arg2, . . ., type n arg n)
Example 2
Example 3
Function Prototypes
• In the examples seen before, the function
definition precedes the main() function.
• However, we can define the function after the
main function too ……….. PROVIDED!!!!!
WE “DECLARE” THE FUNCTION BEFORE
MAIN… WHY??
Function Calls
• A function can be called within another
function or the main() function.
• The main() function is the first function the
compiler will start execution from.
When called with swap(x, y); When called with swap(&x, &y); where x and y
x and y will remain the same are int values, then a points to x and b points
to y, so the values pointed to are swapped,
not the pointers themselves
Passing Arrays – call by value
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Passing array to function using call by reference
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
How to pass an entire array to a function as an argument?
#include <stdio.h>
void myfuncn( int *var1, int var2)
{ /* The pointer var1 is pointing to the first element of * the
array and the var2 is the size of the array. In the * loop we
are incrementing pointer so that it points to * the next
element of the array on each increment. * */
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x,*var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Passing 2D Array to Functions
#include <stdio.h>
const int n = 3;
void print(int arr[3][3], int m)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", arr[i][j]);
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}
First Dimension is Optional
#include <stdio.h>
const int n = 3;
void print(int arr[][n], int m)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", arr[i][j]);
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}
Recursive Functions