Functions
Functions
-Functions in C
Functions
Introduction to modular programming, writing
functions, formal parameters, actual parameters.
Pass by Value, Recursion, Arrays as Function
Parameters.
structure, union.
Storage Classes, Scope and life time of
variables simple programs using functions.
2
Modular Programming
●
Dividing a large problem into sub-problems and developing
subprogram for each of the sub-problems.
●
If the sub-problems itself is large enough, then it can further
divided into smaller problems.
●
Advantages :-
●
Modules can be written and tested separately.
●
Modules can be reused.
●
Reduces the length of the program making it more readable.
●
Program maintenance is easier.
●
Several programmers can work on the same
program ,each programmer is working on
separate modules.
Modular Programming
●
Advantages :-
●
Many programs require that a particular group of instructions
be accessed repeatedly, from several different places within
the program.
●
The repeated instructions can be placed within a single
function, which can then be accessed whenever it is needed.
●
Moreover, a different set of data can be transferred to the
function each time it is accessed.
●
Thus, the use of a function avoids the need for redundant
(repeated) programming of the same instructions.
4
Modular Programming
●
Different languages uses different terms for
representing the subprograms.
●
Subroutines
●
Procedures
●
Functions
●
In C language only one kind of subprograms, namely
functions.
●
Decomposition of a program into individual program
modules is generally considered to be an important part
of good programming practice.
5
Functions in C
Modular
Programming :
Types of functions
•User-defined functions
Standard Library function
•The standard library functions are built-in functions in C
programming.
•Hence, to use the printf()function, we need to include the stdio.h header file
using #include <stdio.h>.
•The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
User-defined functions
●
actual arguments
Function Declaration ( Prototype)
●
Function declaration is required
●
when the function is called before its definition and
●
if the type of value returned by the function is other than
int or char.
●
General form of function declaration is:
●
data_type fname(type1 arg1, type2 arg2, ......typen argn);
●
Function declaration in ANSI format (as given above) is called
function prototype
●
It can also be written as
●
data_type fname(type1, type2, ......, typen);
●
Function Example 1
// function for finding the sum of two integer numbers.
#include
<stdio.h> void
main()
{
int a, b,
s;
printf(“Enter Two Numbers
: “); scanf(“%d%d”,
&a,&b);
s = sum(a,b); // a, b – actual
int sum(int x,
parameters // x, y – formal
printf(“Sum = %d\n”, s);
int
} y) parameters
{
return x+y;
}
Function Example 2
// function for finding the largest of three integer numbers.
#include
<stdio.h> void
main()
{
int a, b,
c;
printf(“Enter Three Integers : “);
scanf(“%d%d%d”, &a, &b, &c);
printf(“Largest = %d\n”,
int largest(int a, int b,
largest(a,b,c)); // formal parameters can have any
int
{
} c)int lar; name
lar = a>b? a>c?a:c :
b>c?b:c; return lar;
}
Function Example 3
// function for converting a charater to upper
case.
#include
<stdio.h> void
main()
{ char str[50]; int i;
printf(“Enter a string
: “); scanf(“ %[^\
n]”, str);
for (i=0; str[i] != ‘\0’ ;
i++) str[i] =
char uppercase(char ch)
uppercase(str[i]); // ‘a’ - ‘A’
{ printf(“Upper case string : is
return
%s\n”,ch>=’a’
str); 32
&& ch <=’z’ ?
} ch-32 : ch;
}
Function Example 4
// function for finding the average of two integers.
#include <stdio.h>
float average(int, int); // function
declaration. void main()
{ int a, b; float avg;
printf(“Enter two
integers : “); scanf(“%d
%d”, &a, &b);
avg = average(a,b);
printf(“Average = %f\n”,
avg);
}
4! = 4 x 3!
=4x3x 2!
=4x3x 2 x 1!
=4x3x 2x1
=4x3x 2
=4x6
= 24
Recursion- Example 1
//Recursive function for
finding n! long int
factorial(int);
void main()
{ int n; long fact; factorial(3)
3*factorial(2)
printf(“Enter n :
“);
3*2*factorial
scanf(“%d”,&n
(1) 3*2*1
); fact =
} factorial(n);
longprintf(“%d ! = k)
int factorial(int
{ %ld\n”,n,fact);
if (k)
return k*factorial(k-1);
else
return 1;
}
Recursion- Example 2
int string_length(char
s[ ]); void main()
{
char str[80];
int len; printf(“Enter
a String : ”);
scanf(“ %[^\n]”, str);
len = string_length(str);
printf(“Length of string = %d\
n”, len);
}
int string_length(char s[ ])
{ int i;
for (i=0; s[i] != ‘\0’;
i++); return i;
}
Array as Parameter
// Function for reversing a string.
void string_reverse(char
void string_reverse(char s[ ])
s[ ]); void main() {
{ int L=0, R; char
char str[80]; int ch;
len; printf(“Enter a for (R=0; s[R]!=’\0’;
String : ”); R++)
scanf(“ %[^\n]”, str); ;
string_reverse(str); R--; // points to
printf(“Reversed last char while (L<R)
string : %s\n”, str); { ch =s[L];
} s[L]=s[R];
} s[R]=ch;
return
} ; L++; R--;
Passing 2D Array to
● Function
In case of a multi-dimensional array, the formal argument
declarations within the function definition must include explicit
size specifications in all of the subscript positions except the
first.
●
In case of 2D array (formal parameter) we have to specify the
number of columns.
●
These size specifications must be consistent with the
corresponding size specifications of the actual arguments.
●
The first subscript position may be written as an empty pair
of square brackets, as with a one-dimensional array.
●
The corresponding function prototypes must be written in
the same manner.
Passing 2D Array to
Function void read_mat(int a[ ][10], int m,
// Sum of two matrices int n)
{ int i,j;
void read_mat(int a[ ][10], int m, int n); printf(“Enter matrix of
void sum_mat(int a[ ][10], int b[ ][10], int order”); printf (“ %d x
m, int n); %d\n”, m,n);
void display_mat(int a[ ][10], int m, int n); for (i=0; i<m; i++)
for (j=0; j<n; j++)
void main() } scanf(“%d”, &a[i]
{ int a[10][10], b[10][10], c[10][10]; [j]);
int m, n; void
returnsum_mat(int
; a[ ][10], int
b[ ][10],
int c[ ][10], int m, int n)
printf(“Enter order of Matrix : ”); { int i,j;
scanf(“%d%d”, &m, &n); for (i=0; i<m; i++)
read_mat(a,m,n); for (j=0; j<n; j++)
read_mat(b,m,n); c[i][j]=a[i][j] +
sum_mat(a,b,c,m,n); b[i][j];
printf(“Sum is :\n”); }
display_mat(c,m,n); void display_mat(int a[ ][10], int
} m, int n)
{ ........
Passing Individual Array Elements
•Passing array elements to a function is similar to passing variables to a function.
Passing Arrays to Functions
Pass Multidimensional Arrays to a Function
Parameter Passing
●
In general mainly two kinds of parameter passing
●
Passing by value
●
Passing by reference
●
Passing by value :
●
Value of actual parameter is copied to formal parameter.
●
Any changes made to formal parameter does not affect the
value of actual parameter.
●
C language supports this kind of parameter passing.
●
Passing by referrence:
●
Address of actual parameter is copied to formal parameter.
●
Any changes made to formal parameter affect the value
of actual parameter.
Pass by value
•The value of the actual parameters is copied into the formal
parameters.
•We can not modify the value of the actual parameter by the formal
parameter.
void
modify(int);
void main()
{ Outpu
int a=10; t:
a=10
printf(“a=%d\ After function
n”,a); call. a=10
modify(a);
printf(“After
void
function
modify(int
call.\n
k) a=%d”,a);
}
{
k=200;
}
Excercise on 1D and 2D Array passing
●
Function for finding/doing
●
Smallest element in an array.
●
Average of numbers in an array.
●
Linear Search.
●
Coverting all letters of a string to uppercase.
●
Concatinating one string to another.
●
Matrix multiplication.
●
Checking whether a square matrix is symmetric.
●
Finding largest element in a matrix.
●
Finding sum of major diagonal elements of a square
matrix.
●
String sorting