C (programming language)

Function’s in C with Exercises and Solutions

1. Understanding Functions in C

Functions are the building blocks of modular programming in C. They encapsulate a specific task or set of instructions, reducing code repetition and improving program organization. By breaking down your program into smaller, well-defined functions, you make it easier to understand, maintain, and debug.

1.1 Function Anatomy

A basic C function definition consists of five elements:

  • Return type: The data type of the value (if any) returned by the function. void indicates no return value.
  • Function name: A unique identifier for the function.
  • Parameter list (optional): A comma-separated list of variables that receive values when the function is called.
  • Function body: The block of code containing the instructions executed when the function is called.
  • Closing brace: Marks the end of the function definition.

Here’s an example of a function that calculates the area of a rectangle:


double area_of_rectangle(double length, double width) {
  return length * width;

This function:

  • Takes two double-precision floating-point numbers (length and width) as input.
  • Calculates their product and returns it as a double-precision floating-point value.
  • Can be called from anywhere in your program by its name (area_of_rectangle).

1.2 Function Calls

To execute a function, you call it by its name followed by parentheses. If the function expects parameters, pass their values within the parentheses:


double square_area = area_of_rectangle(5.0, 4.0); // Calculate area of a 5x4 rectangle
printf("Area of square: %f\n", square_area); // Print the calculated area

This code calls the area_of_rectangle function twice, first with arguments 5.0 and 4.0 to calculate the area of a rectangle, and then with 5.0 twice to calculate the area of a square.

2. Function Parameters and Arguments

2.1 Passing Arguments by Value

By default, arguments are passed to functions by value. This means a copy of the argument’s value is created inside the function, and any changes made within the function do not affect the original value.


int x = 10;
void increment_by_one(int a) {

increment_by_one(x); // Pass copy of x's value (10)
printf("x: %d\n", x); // x unchanged (still 10)

2.2 Passing Arguments by Reference

To modify the original variable outside the function, you can pass arguments by reference using the & operator before the variable name. This makes the function work directly with the original memory location of the variable.


int x = 10;
void increment_by_one(int *a) {
  (*a)++; // dereference pointer to access and modify original value

increment_by_one(&x); // Pass address of x using & operator
printf("x: %d\n", x); // x updated to 11

3. Local Variables and Scope

Variables declared inside a function are local to that function and are only accessible within its scope. They are destroyed when the function exits.


void print_message() {
  int message_length = 10; // local variable, accessible only within this function
  printf("This is a message of length %d.\n", message_length);

int main() {
  print_message(); // message_length not accessible here
  // message_length = 20; // invalid, variable not in scope

4. Control Flow Statements in Functions

Functions can use the various control flow statements available in C, such as if, else, for, while, switch, and break, to make decisions and iterate over loops.


int factorial(int n) {
  if (n == 0) {
    return 1;
  } else {
    return n * factorial(n - 1); // recursion example

int main() {
  int num = 5;
  int result = factorial(num);
  printf("Factorial of %d: %d\n", num, result);

5. Recursion

The factorial example demonstrated basic recursion. Remember, functions should avoid infinite recursion by having a clear base case to terminate the repetitive calls.

6. Predefined Functions and Libraries

C offers many built-in functions and libraries, including printf, scanf, sqrt, pow, and string manipulation functions. These pre-defined functions extend your capabilities and reduce the need for repetitive code.

Exercise: Write a program that uses scanf to input two numbers and printf to display their sum, difference, product, and quotient.

7. Static Functions and Variables

Static functions and variables have function scope but are declared with the static keyword. This means they retain their values even after the function exits.


static int counter = 0;

int next_number() {
  return counter;

int main() {
  int a = next_number();
  int b = next_number();
  printf("a: %d, b: %d\n", a, b); // a: 1, b: 2 (counter remembers its state)

Exercise: Modify the above program to use a static variable to store the sum of all numbers returned by next_number.

8. Function Pointers

Function pointers store the memory address of a function. They allow you to dynamically call functions based on certain conditions.


int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }

int (*operation)(int, int) = &add; // pointer points to add function

int result = operation(5, 3); // function call through pointer

if (is_negative(result)) {
  operation = &subtract; // change pointer to subtract function

Exercise: Write a program with a function pointer that calls either add or subtract based on user input (+ or -).

9. Advanced Function Topics

C offers additional function features like:

  • Variable-length argument lists (stdarg.h): Handle functions with a dynamic number of arguments.
  • Inline functions: Small functions directly inserted into the calling code for efficiency.
  • External functions and header files: Declare functions shared across multiple source files.

These topics extend your understanding of functions and enhance program modularity and flexibility.

Recap and Conclusion

Functions are essential building blocks for modular and organized C programs. They encapsulate tasks, improve code reusability, and simplify program structure. This guide provided a foundation for understanding functions, including parameters, scope, control flow, recursion, and advanced features. By practicing the exercises and exploring further, you can master functions and leverage their power to build efficient and well-structured C programs.

Remember, the key to mastering functions is to practice and experiment. Don’t hesitate to explore additional resources and challenges to solidify your understanding and unleash the full potential of functions in your C programming journey.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button