1.5 Functions in C
Module 1.5 • Modularity, Parameters, Scope Rules & Recursion
1.5.1 Introduction
As programs become larger, writing all statements inside the main() function makes code difficult to understand and maintain. To solve this problem, C provides functions.
A function is a named block of code designed to perform a specific task. Functions help programmers divide a large problem into smaller manageable units.
Benefits of Functions
- Improve program readability.
- Reduce code duplication.
- Simplify debugging and testing.
- Enable code reuse.
- Support modular programming.
For example, instead of writing code to calculate an average multiple times, we can create a function and call it whenever needed.
1.5.2 Components of a Function
Every function generally consists of:
- Function Declaration (Prototype)
- Function Definition
- Function Call
General Syntax
return_type function_name(parameter_list)
{
statements;
return value;
}
Example
int square(int n)
{
return n * n;
}
Here:
int→ Return typesquare→ Function namen→ Parameterreturn n * n→ Returned value
1.5.3 Function Declaration
A function declaration informs the compiler about:
- Function name
- Return type
- Number of parameters
- Parameter data types
Syntax
return_type function_name(type1, type2);
Example
float calculateArea(float);
The declaration is usually written before main().
1.5.4 Function Definition
The function definition contains the actual code that performs the task.
Example
#include <stdio.h>
int cube(int n)
{
return n * n * n;
}
int main()
{
printf("%d", cube(4));
return 0;
}
Output
64
1.5.5 Function Call
A function call transfers control from the calling function to the called function.
Example
#include <stdio.h>
void displayMessage()
{
printf("Welcome to C Programming");
}
int main()
{
displayMessage();
return 0;
}
Output
Welcome to C Programming
1.5.6 Library Functions and User-Defined Functions
Functions in C are broadly classified into two categories.
A. Library Functions
These are predefined functions provided by C libraries.
Examples
| Function | Purpose |
|---|---|
printf() | Display output |
scanf() | Read input |
strlen() | Find string length |
sqrt() | Calculate square root |
pow() | Calculate powers |
Example
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.2f", sqrt(81));
return 0;
}
Output
9.00
B. User-Defined Functions
Functions created by programmers for specific tasks.
Example
#include <stdio.h>
void line()
{
printf("------------------");
}
int main()
{
line();
return 0;
}
1.5.7 Categories of Functions
Functions are commonly classified into four types.
Type 1: No Arguments and No Return Value
Example
#include <stdio.h>
void welcome()
{
printf("Good Morning");
}
int main()
{
welcome();
return 0;
}
Output
Good Morning
Type 2: No Arguments but Return Value
Example
#include <stdio.h>
int getNumber()
{
return 25;
}
int main()
{
int num;
num = getNumber();
printf("%d", num);
return 0;
}
Output
25
Type 3: Arguments but No Return Value
Example
#include <stdio.h>
void printSquare(int n)
{
printf("Square = %d", n * n);
}
int main()
{
printSquare(7);
return 0;
}
Output
Square = 49
Type 4: Arguments and Return Value
Example
#include <stdio.h>
int maximum(int a, int b)
{
if(a > b)
return a;
else
return b;
}
int main()
{
printf("%d", maximum(18, 11));
return 0;
}
Output
18
1.5.8 Actual and Formal Parameters
Actual Parameters
Values supplied during a function call.
result = add(12, 8);
Here 12 and 8 are actual parameters.
Formal Parameters
Variables declared in the function definition.
int add(int x, int y)
Here x and y are formal parameters.
1.5.9 Return Statement
The return statement sends a value back to the calling function.
Example
#include <stdio.h>
int multiply(int a, int b)
{
return a * b;
}
int main()
{
printf("%d", multiply(6, 5));
return 0;
}
Output
30
Notes
- A function can return only one value directly.
- return immediately terminates function execution.
- Functions with void return type do not return values.
1.5.10 Scope of Variables
Variables can be classified based on where they are declared.
Local Variables
Declared inside a function.
Example
void test()
{
int value = 20;
}
The variable value exists only inside test().
Global Variables
Declared outside all functions.
Example
#include <stdio.h>
int count = 100;
void show()
{
printf("%d\n", count);
}
int main()
{
show();
return 0;
}
Output
100
All functions can access global variables.
1.5.11 Static Variables
A static variable retains its value between function calls.
Example
#include <stdio.h>
void counter()
{
static int n = 1;
printf("%d\n", n);
n++;
}
int main()
{
counter();
counter();
counter();
return 0;
}
Output
1
2
3
Unlike ordinary local variables, static variables are initialized only once.
1.5.12 Recursive Functions
A recursive function is a function that calls itself.
Example: Factorial Using Recursion
#include <stdio.h>
long factorial(int n)
{
if(n == 0)
return 1;
return n * factorial(n - 1);
}
int main()
{
printf("%ld", factorial(6));
return 0;
}
Output
720
1.5.13 Advantages of Recursion
- Simplifies complex problems.
- Produces shorter code.
- Useful for mathematical computations.
- Helpful for tree and graph algorithms.
Applications
- Factorial calculation
- Fibonacci series
- Tower of Hanoi
- Tree traversal
1.5.14 Example: Fibonacci Number
#include <stdio.h>
int fibonacci(int n)
{
if(n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main()
{
printf("%d", fibonacci(7));
return 0;
}
Output
13
1.5.15 Function Nesting
A function can call another function.
Example
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int doubleSum(int x, int y)
{
return add(x, y) * 2;
}
int main()
{
printf("%d", doubleSum(5, 7));
return 0;
}
Output
24
1.5.16 main() Function
Every C program starts execution from the main() function.
Example
int main()
{
return 0;
}
Key Points
- There must be only one main() function.
- Program execution begins from main().
- Returning 0 indicates successful execution.
1.5.17 Good Practices for Writing Functions
Use Meaningful Names
Good: calculateTotal(), findLargest()
Avoid: abc(), fun1()
Keep Functions Small
Each function should perform one specific task.
Avoid Repetition
Create reusable functions instead of writing identical code repeatedly.
Add Comments
Document complex logic for easier maintenance.
1.5.18 Real-World Applications of Functions
Functions are extensively used in:
- Banking systems
- Payroll software
- Inventory management
- Scientific calculations
- Mobile applications
- Embedded systems
- Operating systems
Large software projects may contain thousands of functions working together.
Summary
- Functions are reusable blocks of code designed to perform specific tasks.
- A function consists of declaration, definition, and call.
- Functions improve modularity, readability, and maintenance.
- Functions may or may not accept arguments and may or may not return values.
- Variables can be local, global, or static.
- Recursive functions call themselves to solve smaller versions of a problem.
- Every C program begins execution from the main() function.
- Proper use of functions leads to efficient and well-structured programs.
Click your choice for each question to view feedback immediately. Complete all questions to evaluate your metric score.