Concept
of Function in C
Imagine trying to develop a huge program like the Windows
or Mac OS with hundreds of thousands (or millions of lines of code). No way to
do it all in one big program file. Is the work of hundreds of computer
programmers, each working on smaller pieces of the problem that are then
brought together.
What
is a Function?
A function is a block of code that has a name and it has
a property that it is reusable i.e. it can be executed from as many different
points in a C Program as required.
A complex problem is often easier to solve by dividing it
into several smaller parts, each of which can be solved by itself.
main()
function uses these functions to
solve the original problem.
There
are two type of function
1)Built in function
2)User Defined function
Built
in Function:
C has many built-in functions that you can use in your
programs.
main()
printf(), scanf(), pow() etc…..
User
Defined function
If you have a special set of instructions that aren’t in
a built-in function, you can create a user-defined function. Here are the
steps:
A function definition has the following syntax:
<type>
<function name>(<parameter list>){
<local
declarations>
<sequence
of statements>
}
For example: Definition of a function that computes the
absolute value of an integer:
int absolute(int x){
if (x >= 0) return x;
else return -x;
}
Why Should we use function in C?
1)Break a large problem into smaller pieces.Smaller
pieces sometimes called ‘modules’ or ‘subroutines’ or ‘procedures’ or functions
2) Helps manage complexity, Smaller
blocks of code and Easier to read
3) Encourages re-use of code
4) Allows independent development of code
5) Provides a layer of ‘abstraction’ for example a=sqrt(9.0);
Functions
Structure
Functions -Mathematical View
Functions - Example



No comments:
Post a Comment