Functions in C: solved exercises step by step
Functions in C: solved exercises step by step
If you searched for C functions solved exercises, here are the patterns that appear in any introductory C exam.
The goal is to master four key situations: void functions, functions that return a value, pass by value, and pass by reference using pointers.
Problem statement
Solve these 4 mini exercises using functions:
- print a greeting (
voidfunction with no parameters), - compute the square of a number (function with return value),
- swap two integers (pass by reference with pointers),
- compute the factorial of
niteratively.
C solution
Expected output
Common mistakes
- Forgetting to declare the function prototype before
mainwhen it is defined afterward. - Confusing pass by value with pass by reference: modifying the local parameter does not change the original variable.
- Omitting
returnin non-void functions. - Using
voidas the return type when the function actually returns something.
Practical use
Functions are the foundation of any real C program:
- they split logic into reusable blocks,
- they allow pass by reference to modify the caller’s variables,
- they make unit testing and maintenance much easier.
Mastering pass by reference with pointers is essential before working with arrays and data structures.
Recommended next exercise
- Switch case in C: solved exercise
- Pointers in C: solved exercises
- Recursion in C: solved exercise
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
When should I use void as the return type?
When the function does not need to return any value to the caller: it prints output, modifies variables by reference, or performs an action with no result.
What is the difference between pass by value and pass by reference?
Pass by value copies the data; the function works on the copy and the original is unchanged. Pass by reference passes the memory address (&variable) and the function can modify the original through the pointer.
Can a C function return more than one value?
Not directly. The usual approach is to return one value via return and the rest by reference (pointers), or group them in a struct.