COMPUTER SCIENCE – 12
Chapter 13
Functions in C
Contents
Function
Types of Functions
Function Prototype / Declaration
Function Definition
Function Call
Passing Arguments / Parameters to Function
Returning Value from Function
Local Variables
Global Variables
Function
A piece of code within a program, which is written to perform a specific task
Independent of remaining code of the program
Functions are building blocks of C program
A program may contain many functions
Each function has a unique name
Called for executing with the reference to its name
Can be called for executing by main() function or any other function of program
Functions provide structured programming approach
Structure programming a large program is divided into smaller units
Small units functions or modules, or subprograms
Function
Importance of Function
If a program is written without using functions may be repetition of same piece of code at
various places
Size of program may become very large
Becomes very difficult to modify and debug program
Using functions, a program can be divided into different units
Each unit can be managed easily
A piece of code for each unit is written as a function
Same piece of code is written only once in program as a function
Can be called again and again from multiple places in a program to perform a particular task
Size of program is reduced
Program can easily be modified and debugged
Benefits / Advantages of Using Functions
+ Easy to write a program
+ Problem becomes easier if it is broken down into smaller tasks
+ Writing a large program becomes easier if it is divided into smaller parts
+ Each part is called a function
+ Easy to understand and modify the program
+ When large program is divided into subprograms complexity of program is reduced
+ Makes easier to understand the logic of the program
+ Also easy to make changes and detect errors in program
+ Eliminate duplicate code
+ Same piece of code is written only once in program as a function
+ Function is called for executing with the reference to its name only
+ Same piece of code does not have to be written at multiple places to perform the same task
+ Reduces size of program
+ Reusability
+ Function written for one program can be re-used into another new program
+ Programmer can develop a program quickly in a very short time
Types of Functions
Q.3 Explain different types of functions in C.
Types of Functions
Built-in Functions
Predefined functions that are part of programming language
Library functions
Can be used for different purposes
Make the programmer’s job easier to design the program
Program development time is also reduced by using built-in functions
A large number of built-in functions
Declared in header files
For example,
‘printf()’ and ‘scanf()’ functions declared in “stdio.h”
‘clrscr’ function declared in “conio.h”
C-language has a large number of header files
Each header file has information of related functions
Types of Functions
User-Defined Functions
Functions written by a user or programmer
Programmer-defined functions
User-defined function is written to perform a specific task
A program may contain many user-defined functions
Parts of user-defined function
Function Declaration or prototype
Function Definition
Function Prototype / Declaration
Q.4 What is function prototype / declaration? Explain with examples.
Function Prototype / Declaration
Prototype means sample or model
Function prototype Specifying structure or model of a user-defined function
Function declaration
Like variables, functions should be declared before they are defined
Function declaration statement is used to declare a user-defined function
Provides the information to compiler about user-defined function
Name of function
Data type returned by function
Number and types of parameters used in function
General syntax return-type function-name(parameter list);
Function can be declared before main() function or inside it (or inside any user-defined function)
Function declaration is omitted if function definition is written before main() function
Function Prototype / Declaration
Examples
int power(double, int);
name of function power
return data type int
number of parameters two: first of double type and second of int type
float temp(void); OR float temp();
name of function temp
return data type float
Empty parentheses or keyword void indicates function takes no argument
void display(void); OR display();
name of function display
return data type void, i.e. it does not return any value
Empty parentheses or keyword void indicates function takes no argument
Function Definition
Q.5 What is the function definition? Explain with example.
OR Describe the process of writing a function in C-language.
Q.6 Differentiate between function definition and function declaration.
Function Definition
Actual code or set of statements that is written for a function to perform a specific task
Always outside the main() function
Can be written before or after the main function
If function definition is written before main() function, function declaration is omitted
Function definition can also be written in a separate file
If function definition is stored in a separate file, it is included in program using “#include”
preprocessor directive
Parts of function definition
Function header
Function Body
Function Definition
Function Header
First line of function definition function header or function declarator
Same as function declaration but not terminated by semicolon (;)
Function Body
Set of statements that are written between curly braces just after the header of function
definition
Statements are written to perform a specific task
Function Definition
Example
Function Header int cube(int n)
Function Body Three statements enclosed in braces
The main() function is also a function that contains main body of program
Similar to function definition of user-defined function
Difference between Function
Definition and Function Declaration
Function Definition Function Declaration
Set of statements that is written to Single statement that specifies name of
perform a particular task function, its parameters along with their
data types and the return data type of
Must be defined before or after main()
function
function
Its use is optional if function definition is
Cannot be written inside main()
placed before main() function
function
Can be written within main() function
Function Call
Q.7 How is a function called for execution? OR What is a function call?
Function Call
Process to execute a function to perform a specific task
A function is called with reference to its name
If a function has parameters actual values in form of variables or constants are also given in
parentheses after name of function
If a function has no parameter parentheses are left blank
If a function returns a value can be called in an arithmetic expression, or can directly be called
in an output function such as printf()
When C compiler compiles program, it generates a special code at function call to jump to
function definition
When function is called for execution, control transfers to function definition and its statements
are executed
After executing function statements, control transfers back to calling function
Function that calls another function through function call statement calling function
Function Call
Example
Function Call
Passing Arguments / Parameters to
Function
Q.7 How are arguments / parameters passed to the function?
Q.8 Differentiate between formal parameters and actual parameters of a
function.
Passing Arguments / Parameters to Function
An argument / parameter is a piece of data passed to function
If a function uses arguments then variables must be declared in function header to receive the
values
Types of parameters /arguments
Formal Parameters / Arguments
Parameters used in function header
Used to receive values from calling function
Actual Parameters / Arguments
Parameters used in function call
Actual values that are passed to function
May be in form of constant values or variables
Data types of actual parameters must match with corresponding data types of formal parameters
(variables) in the function definition
Passing Arguments / Parameters to Function
Example
Difference between Formal
Parameters and Actual Parameters
Formal Parameters Actual Parameters
Used in function header Used in the function call
Used to receive values that are Actual values that are passed
passed to function through to function definition through
function call function call
Treated as local variables of a May be constant values or
function in which they are used variable names (local or global)
in function header
Passing Arguments / Parameters to Function
Returning Value from Function
Q.9 How does a function return value? Also describe the ‘return’
statement.
Q.10 How would you call a function that returns a value? Explain with
example.
Returning Value from Function
When a function completes its execution , it can return a single value to calling function (or
program)
May be a calculated answer of a formula or any value
Type of data that a user-defined function returns must be declared in function prototype and
function definition
Data type of a function is declared in same way as type of variable is declared
For example: int sum(int, int);
Return data type is also specified with function header in function definition
Return data type in function definition must be same as given in function declaration
Returning Value from Function
The ‘return’ Statement
Used in body of function to return a value as well as execution control to calling function
Used as the last statement of the function
General syntax return expression;
If a function does not return any value (or its return data type is “void”) then control is returned
back to calling function after executing last statement of function
Control also returns to calling function if “return” statement is encountered in any location of the
body of function
Statements after ‘return’ statement are not executed
Calling Function that Returns Value
The function that returns a value can be called for execution in any one
of the following ways:
Calling Function that Returns Value
Local Variables
Q.11 What are the local variables? Explain scope and lifetime of local
variable.
Local Variables
Variables that are declared inside the function
Variables declared in header of function definition are also treated as local variables of that function
Local variables can only be used in function in which they are declared
Automatic variables keyword auto can be used to declare these variables
Use of auto is optional
Scope of Local Variable
Portion of a program where a variable is used (accessed) is known as its scope
A local variable declared in a function can only be used in that function only
Lifetime of Local Variable
Time period for which a variable exists in memory
Lifetime of a variable starts when it is created in memory
Ends when it is destroyed from memory
A variable can only be used during its lifetime
Local variables are created when control enters into function
Destroyed from memory when control returns back to calling function
When same function is called again local variables are created again
Local Variables
Global Variables
Q.12 What are global variables? Explain scope and lifetime of global variable.
Global Variables
Variables that are declared outside main() function or any other function
Global variables or external variables
Hold their values during the entire execution of program
Values of global variables can be shared among different functions
If any function changes the value of a global variable modified value is also available to other
functions
Use of global variables is not recommended, because:
Accessible to all functions and becomes difficult to track changes in their values
Occupy a large amount of memory permanently during program execution
Data accessing speed of program may become slow
Scope of Global Variable
Can be used by all functions in programs has a file scope
Lifetime of Global Variable
Time period for which a global variable exists in memory
Lifetime of global variables is between starting and terminating of a program execution
Global Variables
Comparison between Local and
Global Variables
Local Variables Global Variables
Declared inside main() function or any Declared outside the main() function or
other user-defined function any other user-defined function
Can be used or accessed in function in Can be used or accessed in any function
which they are declared of the program
Created into memory when control enters Created into memory when program
into function or block in which they are execution starts
declared Destroyed from memory when program
Destroyed from memory when control exits execution is terminated
function or block Values of global variables can be shared
Values of local variables cannot be shared among other functions
among other functions Use of global variables is not
Use of local variables is recommended recommended during program designing
during program designing
Assignment
Write a program that inputs a number and passes that number to the function. The function
displays the table of a given number.
Write a program that inputs a number and passes the number to a function. The function
calculates the factorial and displays the result.
Write a program that inputs two numbers and passes these numbers to a function. The function
displays the result of first number raise to the power of second number.
Write a program that inputs base and height of a triangle and passes them to a function. The
function calculates the area of triangle and returns the result to the calling function.
Formula to compute area of triangle = ½ (base *height)
Write a function Is_Prime that has an input parameter i.e num, and returns a value of 1 if num is
prime. Otherwise returns a value of 0.
Write a program that prompts the user to enter a number and calls a function Factorial() to
compute its factorial. Write the function Factorial() that has one input parameter and returns the
factorial of the number passed to it.
Write a program that prompts the user for the Cartesian coordinates of two points (x1, y1) and
(x2, y2) and displays the distance between them. To compute the distance, write a function
named Distance( ) with four input parameters. The function Distance() uses the following distance
formula to compute the distance and returns the result to the calling function:
Assignment
Write a function GCD that has two input parameters and returns the
greatest common divisor of the two numbers passed to it. Write a
complete C program that inputs two numbers and call the function GCD
to compute the greatest common divisor of the numbers entered.
Write a program that prompts the user to enter a number and then
reverses it. Write a function Reverse() to reverse the number. For
example, if the user enters 2765, the function should reverse it so that it
becomes 5672. The function should accept the number as an input
parameter and return the reversed number.
Write a complete C program that inputs two integers and then prompts
the user to enter his/her choice. If the user enters 1 the numbers are
added, for the choice of 2 the numbers are subtracted, for the choice of
3 the numbers are multiplied, for the choice of 4 the numbers are
divided. Write four functions Add(), Subtract(), Multiply() and Divide() to
complete the task.
For more details, and solved assignment refers to
PM Series
Computer Science
ICS Part-II
by
CM Aslam, Aqsa Aslam, Abdur Rehman &
Mudassir Saleem
Publisher: Majeed Sons
22- Urdu Bazar, Lahore