Functions
What is a function in C?
A function is a self-contained block of code designed to perform a specific task. It can receive data through parameters and may return a result to the calling function. Functions help a programmer divide a large program into smaller tasks, reuse code, and write programs that are easier to understand, test, and maintain.
Think of a function like a calculator: you provide input, it performs a task, and it may give you an answer.
- Input: two numbers, 10 and 20.
- Function: add() calculates 10 + 20.
- Output: Result = 30.
Designing structured programs using functions
Definition:A structured program divides a complex problem into smaller modules. Each function handles one responsibility, and the functions work together to solve the complete problem.
For example, a student marks program can be divided into three functions:
- main(): coordinates the program.
- Read marks: input function.
- Calculate: processing function.
- Display result: output function.
Advantages of structured programming
- Modularity: Break a large program into smaller functions.
- Reusability: Call a function multiple times instead of repeating code.
- Readability: Give functions meaningful names.
- Testing: Test individual functions separately.
- Maintenance: Modify one function without unnecessarily changing the entire program.
Library functions and user-defined functions
C programs can use two broad categories of functions:
Library functions
Functions supplied by the C standard library.
Examples: printf(), scanf(), strlen(), sqrt().
Examples of headers: stdio.h, string.h, math.h.
User-defined functions
Functions written by the programmer to perform a particular task.
Examples: add(), calculateAverage(), findMaximum().
The programmer defines the function's name, parameters, and operations.
Example of a user-defined function:
int add(int a, int b)
{
return a + b;
}
This function receives two integers and returns their sum.
Passing Values Between Functions in C
In C programming, passing values between functions means sending data from one function to another so that the receiving function can perform a calculation or task using that data.
In C, values are commonly passed through function arguments and parameters.
How are values passed between functions
There are three important terms to understand:
- Actual arguments: The values or variables supplied in a function call.
- Formal parameters: The variables declared in the function definition that receive the values.
- Return value: The result sent back to the calling function using the return statement.
Basic function designs
Function definition
A function definition contains the actual code that specifies what the function does.
Syntax:return_type function_name(parameter_list)
{
// Statements
return value;
}
Example:
int square(int n)
{
return n * n;
}
| Component | Meaning |
|---|---|
| int | Return type: the function returns an integer |
| square | Function name |
| int n | Parameter that receives the input |
| return n * n; | Calculates and returns the square |
For a void function, no value is returned. For a non-void function, ensure the function returns a suitable value on every path where a result is required.
Function declaration
A function declaration, often called a function prototype, tells the compiler the function's name, return type, and parameter types before it is called.
Syntax:return_type function_name(parameter_types);
Example:
int add(int, int);
This declaration tells the compiler that add() accepts two integers and returns an integer. A declaration can also name its parameters:
int add(int a, int b);
Both forms are valid.
Why is a declaration useful?
It allows the compiler to check that a function is called with compatible arguments and that its return type is used appropriately. It is especially useful when the function definition appears after main() or in another source file.
The function call
A function call transfers control to a function so that its statements can execute.
Syntax:function_name(arguments);
If the function returns a value, the call can be used in an expression or assignment:
result = add(10, 20);
Here:
- add is the function name.
- 10 and 20 are arguments.
- result receives the returned value.
How does a function call work?
- main() calls add(10, 20).
- Parameters receive the arguments: a = 10, b = 20.
- The function calculates: return a + b; gives 30.
- Control returns to main(), and the result is stored in result.
Example 1: C Program for addition using a function
This program demonstrates a function declaration, function call, and function definition together.
#include
/* Function declaration */
int add(int a, int b);
int main(void)
{
int x = 10, y = 20, result;
/* Function call */
result = add(x, y);
printf("Sum = %d\n", result);
return 0;
}
/* Function definition */
int add(int a, int b)
{
return a + b;
}
Output:
Sum = 30
Understand the three main parts
- Declaration:
int add(int a, int b);announces the function's interface to the compiler. - Call:
result = add(x, y);invokes the function and uses its returned value. - Definition:
int add(int a, int b) { return a + b; }contains the implementation of the function.
Example 2: C Program to check whether a number is even
#include
int isEven(int n)
{
return n % 2 == 0;
}
int main(void)
{
int number = 8;
if (isEven(number))
printf("Even number\n");
else
printf("Odd number\n");
return 0;
}
Output:
Even number
The function returns 1 when the number is even and 0 otherwise, because the comparison expression evaluates to an integer truth value in C.
Example 3: C Program to find the largest of two numbers
#include
int maximum(int a, int b);
int main(void)
{
printf("Largest = %d\n", maximum(15, 25));
return 0;
}
int maximum(int a, int b)
{
if (a > b)
return a;
return b;
}
Output:
Largest = 25
Different types of functions
A function are classified into four main categories based on whether it receives arguments and whether it returns a value.
- Without Argument, Without Return
- With Argument, Without Returnn
- Without Argument, With Return
- With Argument, With Return
Type 1: No arguments and no return value
void welcome(void)
{
printf("Welcome to C Programming!\n");
}
Call it using:
welcome();
Type 2: Arguments and no return value
void printSum(int a, int b)
{
printf("Sum = %d\n", a + b);
}
Call it using:
printSum(10, 20);
Output:
Sum = 30
Type 3: No arguments but returns a value
int getNumber(void)
{
return 100;
}
Call it using:
int n = getNumber();
Now n contains 100.
Type 4: Arguments and returns a value
int multiply(int a, int b)
{
return a * b;
}
Call it using:
int result = multiply(5, 4);
Now result contains 20.
Common mistakes to avoid
- Forgetting the semicolon after a function prototype.
- Calling a function with incompatible arguments.
- Using a returned value incorrectly.
- Forgetting to define a user-defined function when its definition is required by the program.
- Declaring a function with one return type and defining it with an incompatible type.
- Confusing parameters (in the function definition) with arguments (in the function call).
- Forgetting that a function's local variables normally exist only within that function's scope.
Difference between function declaration, definition, and call
| Term | Meaning |
|---|---|
| Function | Named block of code that performs a task |
| Function declaration | Announces the function's interface |
| Function definition | Provides the function's implementation |
| Function call | Invokes the function |
| Parameter | Variable listed in a function definition |
| Argument | Value or expression supplied at a call |
| Return value | Result sent back to the caller |
| Modular programming | Organizing a program into separate functions |
Practice questions
- Define a function in C and explain its advantages.
- Explain the four basic function designs with examples.
- Differentiate between a function declaration, definition, and call.
- What are library functions and user-defined functions? Give examples.
- Explain the execution flow of a function call with a suitable program.
- Write a C program to find the largest of two numbers using a function.
- Write a C program to calculate the factorial of a number using a user-defined function.