Until now every program has consisted of one function, main. Real programs are built from many functions that call one another. This section explains what a function is, how to write one and what happens when it is called.
Why functions are needed
Splitting a program into functions is called modular programming. Its benefits:
Benefit
Meaning
Reuse
Write the code once and call it from many places
Readability
average(marks, n) says what happens without showing how
Easier testing and debugging
Each function can be checked separately
Teamwork
Different people can write different functions
Less repetition
A change is made in one place only
Functions are of two kinds: library functions such as printf, sqrt and strlen, which come with the compiler, and user-defined functions, which you write.
Parts of a function definition
Syntax
return-type function-name(parameter-list){ local variable declarations; statements; return expression;}
Part
Meaning
Example
Return type
Type of the value sent back; void if none
int
Function name
An identifier, following the usual naming rules
square
Parameter list
Typed variables that receive the caller’s values; void if none
(int no)
Body
The statements between { and }
return no * no;
The first line, int square(int no), is called the function header.
Calling a function
A function runs only when it is called by writing its name followed by arguments in parentheses, such as sq = square(n);. The function that makes the call is the calling function; the one that runs is the called function.
1main runs until it reaches the call square(n)
→
2main pauses; the value of n is copied into the parameter no
→
3square runs its body
→
4return sends the result back
→
5main resumes at the point of the call
Flow of control in a function call
Key takeaways
Functions split a program into reusable, testable modules.
A definition has a return type, a name, a parameter list and a body.
A function runs only when it is called; control then returns to the caller.
Library functions are supplied; user-defined functions are written by the programmer.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function cube that returns the cube of an integer, and show the statement in main that prints the cube of 4.
Show worked answer
int cube(int n) { return n * n * n; }. In main: printf("%d\n", cube(4));. The call passes 4 to the parameter n, the function computes 4 × 4 × 4 = 64 and returns it, and printf prints 64.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions/defining-and-calling-functions/ to read this page.