3. Functions in C
Functions are a very useful technique in very programming language. Functions are a part of a program, but coded as a separate segment. Hence they are otherwise known as subroutines.
- Modules in C
•
C standard library has a wide
variety of functions
•
Ex: x = pow(4,2) ?
- Programs combine user-defined functions with library functions
Functions, in short modularize a program
3.1 Benefits of functions
- Divide and conquer
- Software reusability
•
Use existing functions as
building blocks for new programs
•
Abstraction - hide internal
details (library functions)
- Avoid code repetition
3.2 More on Functions
¢
A fragment of code that accepts
zero or more argument values, produces a result value, and
has zero or more side effects.
¢
A method of grouping a subset
of a program
•
To hide details
•
To be invoked from multiple places
•
To share with others
¢
Format for calling functions
FunctionName( argument
);
•
Ex: sqrt( 9 )
•
If multiple arguments, use
comma-separated list
3.3 Function definition format
The syntax for defining a function is:
return-value-type
function-name( parameter-list )
{
declarations and statements
}
{
declarations and statements
}
It must noted here that,
¢
Function-name: any valid
identifier
¢
Return-value-type: data type of
the result (default int)
void – indicates that the
function returns nothing
¢
Parameter-list: comma separated
list, declares parameters
Declarations and statements:
function body (block)
•
Variables can be declared inside
blocks
•
Functions can not be defined
inside other functions
Returning control
•
If nothing returned
• return;
• or, until reaches right brace
•
If something returned
•
return expression;
Question 1?
Write a program to find factorial of a number n?
main() {
int n,f=0;
printf(“Enter a number”):
scanf(“%d”,&n);
f=myfactorial(n);
printf(“ The factorial is %d”,f);
No comments:
Post a Comment