🧩 12. Functions in C
Functions are one of the most important building blocks of C programming. They allow us to divide a large program into smaller, meaningful and reusable pieces of code.
A function is a named block of code designed to perform a particular task. Instead of writing the same logic repeatedly, we can place it inside a function and call that function whenever required.
12.1 What Is a Function?
A function is a block of statements that performs a specific operation. It can receive input through parameters and can optionally return a result.
#include <stdio.h>
void greet(void)
{
printf("Hello, CodeBhavya!\n");
}
int main(void)
{
greet();
return 0;
}
Here, greet() is a user-defined function.
When greet() is called, the statements inside its body execute.
greet
void
void — no parameters
The statements inside { }
12.2 Why Do We Need Functions?
Imagine a program that contains 2,000 lines of code.
If all of those statements are written inside main(),
the program becomes difficult to read, test and maintain.
Functions allow us to divide the program according to responsibilities.
main()
{
input code
calculation code
validation code
display code
another calculation
another validation
another display
}
With functions:
main()
{
readData();
calculateResult();
validateResult();
displayResult();
}
Write logic once and call it multiple times.
Function names explain what different parts of a program do.
Individual functions can be tested separately.
Changes can often be isolated to one function.
12.3 Anatomy of a Function
return_type function_name(parameter_list)
{
// function body
statements;
return value;
}
A function can be understood through four major parts:
| Part | Meaning | Example |
|---|---|---|
| Return type | Type of value returned by the function | int |
| Function name | Name used to call the function | add |
| Parameters | Inputs received by the function | int a, int b |
| Function body | Statements executed when called | { ... } |
12.4 Function Declaration
A function declaration tells the compiler about a function before the function is used.
int add(int a, int b);
This tells the compiler that a function named add:
- returns an
int - expects two
intparameters - will be defined somewhere in the program
A function declaration is also commonly called a function prototype.
12.5 Function Definition
The function definition contains the actual implementation.
int add(int a, int b)
{
return a + b;
}
The definition tells the compiler what the function actually does.
| Declaration | Definition |
|---|---|
| Tells what the function looks like | Contains the implementation |
Usually ends with ; |
Contains a function body |
int add(int, int); |
int add(int a, int b) { ... } |
12.6 Calling a Function
A function does not execute merely because it has been defined. It executes when it is called.
#include <stdio.h>
void message(void)
{
printf("Welcome to C Programming!\n");
}
int main(void)
{
message();
return 0;
}
The statement:
message();
is the function call.
Program flow
main()
|
| calls
v
message()
|
| executes printf()
v
returns to main()
|
v
return 0
12.7 Parameters and Arguments
Functions can receive data from the caller. The variables listed in the function definition are called parameters. The actual values supplied during the call are called arguments.
int add(int a, int b)
{
return a + b;
}
int result = add(10, 20);
| Term | Example | Meaning |
|---|---|---|
| Parameter | int a |
Variable receiving a value |
| Parameter | int b |
Variable receiving a value |
| Argument | 10 |
Actual value supplied by caller |
| Argument | 20 |
Actual value supplied by caller |
12.8 Returning a Value
A function can calculate a result and send that result back to its caller
using the return statement.
int square(int n)
{
return n * n;
}
int main(void)
{
int result;
result = square(5);
printf("%d\n", result);
return 0;
}
Execution:
square(5)
|
| n = 5
|
| 5 * 5
v
return 25
|
v
result = 25
The value returned by a function can be stored in a variable, printed, used in another expression, or passed to another function.
12.9 Functions That Return Nothing — void
If a function does not return a value, its return type can be
void.
void display(void)
{
printf("Hello!\n");
}
The first void means the function returns no value.
The second void means it accepts no parameters.
void display(void);
| Declaration | Meaning |
|---|---|
void display(void); |
No return value and no parameters |
void display(int n); |
No return value, one integer parameter |
int display(void); |
Returns an integer, no parameters |
12.10 Functions with Multiple Parameters
A function can receive multiple parameters.
int multiply(int a, int b, int c)
{
return a * b * c;
}
int main(void)
{
int result = multiply(2, 3, 4);
printf("%d\n", result);
return 0;
}
The values are matched with parameters according to their position:
multiply(2, 3, 4)
a = 2
b = 3
c = 4
The number, order and compatible types of arguments should match the function's parameter list.
12.11 Why Do We Need a Function Prototype?
Suppose the function is defined after main().
The compiler needs to know about the function before encountering the
call.
#include <stdio.h>
int add(int a, int b);
int main(void)
{
int result = add(10, 20);
printf("%d\n", result);
return 0;
}
int add(int a, int b)
{
return a + b;
}
The prototype:
int add(int a, int b);
provides the necessary information before the call.
Prototype
|
v
Compiler knows function signature
|
v
main() calls add()
|
v
add() definition appears later
|
v
Function executes
12.12 Defining a Function Before main()
A function can also be completely defined before main().
In that case, the compiler has already seen the definition when it
encounters the call.
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main(void)
{
printf("%d\n", add(5, 7));
return 0;
}
Prototype first, definition later.
Definition first, then main().
12.13 Four Common Function Forms (Categories of User-Defined Functions)
A useful beginner classification is based on whether a function receives arguments and whether it returns a value. There are four categories when we combine these two choices: input through arguments (yes/no) and output through a return value (yes/no).
| Category | Arguments? | Returns a value? | Example declaration |
|---|---|---|---|
| 1. No arguments, no return value | No | No | void greet(void) |
| 2. Arguments, no return value | Yes | No | void printSquare(int number) |
| 3. No arguments, returns a value | No | Yes | int getNumber(void) |
| 4. Arguments and returns a value | Yes | Yes | int add(int a, int b) |
Function categories at a glance:
Does it receive arguments?
/ \
NO YES
| |
Does it return data? Does it return data?
/ \ / \
NO YES NO YES
| | | |
Type 1 Type 3 Type 2 Type 4
Important distinction: A function may display information
with printf() without returning a value to the calling function.
In these examples, void before the name means there is no return
value; void inside the parentheses means the function accepts no
arguments.
Category 1 — No arguments and no return value
The function receives no data from the caller and does not send a result back using return. It performs its task internally, such as displaying a message.
Complete C program:
#include <stdio.h>
/* No arguments and no return value */
void greet(void)
{
printf("Welcome to CodeBhavya!\n");
}
int main(void)
{
greet();
return 0;
}
Output:
Welcome to CodeBhavya!
How it works:
- Execution begins in
main(). greet()is called without arguments.greet()prints the message.- Control returns to
main(); no result is returned bygreet().
void greet(void) has no input parameters and no return value. A printf() statement produces screen output, not a function return value.Category 2 — With arguments and no return value
The calling function supplies one or more values. The called function uses those values to perform an action, but it does not return a result to the caller.
Complete C program:
#include <stdio.h>
/* Arguments but no return value */
void printSquare(int number)
{
printf("Square = %d\n", number * number);
}
int main(void)
{
printSquare(5);
return 0;
}
Output:
Square = 25
How it works:
main()callsprintSquare(5).- The argument
5is copied into the parameternumber. printSquare()calculates5 * 5and prints25.- The function finishes and control returns to
main(), without returning a value.
void function does not return it.Category 3 — No arguments but returns a value
The function does not need any input from the caller. It calculates, retrieves, or supplies a value, and returns that value to the calling function.
Complete C program:
#include <stdio.h>
/* No arguments but a return value */
int getNumber(void)
{
return 42;
}
int main(void)
{
int value = getNumber();
printf("Number = %d\n", value);
return 0;
}
Output:
Number = 42
How it works:
main()callsgetNumber()without arguments.getNumber()executesreturn 42;.- The returned integer is stored in
value. main()printsNumber = 42.
int getNumber(void) returns an integer. The caller may store it, print it, or use it in an expression.Category 4 — With arguments and a return value
The calling function passes input values; the called function processes those values and sends the computed result back. This form is especially useful for reusable calculations.
Complete C program:
#include <stdio.h>
/* Arguments and a return value */
int add(int a, int b)
{
return a + b;
}
int main(void)
{
int sum = add(10, 20);
printf("Sum = %d\n", sum);
return 0;
}
Output:
Sum = 30
How it works:
main()callsadd(10, 20).- Parameters
aandbreceive copies of10and20. return a + b;sends30to the caller.sumstores30andmain()prints the result.
int add(int a, int b) both accepts input and returns an integer. The function itself does not need to print the result.How to identify the category from a function header
| Header | Input to function | Returned result | Category |
|---|---|---|---|
void message(void) | None | None | 1 |
void display(int n) | int n | None | 2 |
float getRate(void) | None | float | 3 |
double average(int x, int y) | int x, int y | double | 4 |
printf("%d", 10); displays 10. The expression
return 10; sends 10 back to the caller. They serve
different purposes.
void appears twice
In void greet(void), the first void means
no return value; the void inside parentheses explicitly means
no parameters.
Ask two questions:
- Does the function receive data?
- Does the function return data?
Those two answers help identify the function form.
Self-check
Identify the category of each function below and check your reasoning.
void show(int age)— arguments, but no return value: Category 2.int readChoice(void)— no arguments, returns a value: Category 3.float area(float radius)— arguments and returns a value: Category 4.void welcome(void)— no arguments, no return value: Category 1.
12.14 Library Functions vs User-Defined Functions
| Library Function | User-Defined Function |
|---|---|
| Provided by C libraries | Created by the programmer |
printf() |
calculateTotal() |
scanf() |
findMaximum() |
strlen() |
isPrime() |
For example, printf() is a library function provided through
the standard I/O facilities, while add() in the following
program is user-defined.
int add(int a, int b)
{
return a + b;
}
12.15 C Uses Pass-by-Value
C passes function arguments by value. That means the function receives a value for its parameter. Changing that parameter does not directly change the caller's ordinary variable.
#include <stdio.h>
void change(int x)
{
x = 100;
}
int main(void)
{
int n = 10;
change(n);
printf("%d\n", n);
return 0;
}
Output:
10
main()
n = 10
|
| value copied
v
change()
x = 10
|
| x = 100
v
x = 100
Back in main:
n is still 10
C does not have a separate "call by reference" parameter mechanism like some languages. C programs commonly achieve modification of caller data by passing addresses through pointers.
12.16 Call by Reference (Using Pointers in C)
In many textbooks, call by reference means allowing a function to modify the original variable in the calling function. In C, we achieve this effect by passing the address of the variable to a function using a pointer parameter.
C always passes arguments by value. When we pass a pointer, the address itself is copied into the pointer parameter. The function can then use that address to change the caller's variable. This is commonly taught as call by reference using pointers, but it is not a separate native parameter-passing mechanism in C.
Syntax and the two important operators
void change(int *p); /* p is a pointer parameter */
change(&number); /* & passes the address of number */
*p = 100; /* * accesses the value at that address */
& is the address-of operator, while * dereferences a pointer to access or modify the value stored at its address.
Complete C program — Modifying the original value
#include <stdio.h>
void change(int *x)
{
*x = 100;
}
int main(void)
{
int n = 10;
printf("Before function call: %d\n", n);
change(&n);
printf("After function call: %d\n", n);
return 0;
}
Output:
Before function call: 10
After function call: 100
How it works, step by step:
main()creates a variablenwith value10.change(&n)passes the address ofnto the function.- The pointer parameter
xstores a copy of that address. *x = 100;writes100to the original variable's memory location.- When the function finishes,
ninmain()is now100.
main() change(int *x)
n = 10 <--- address of n --- x points to n
| |
+------------ *x = 100 ----------+
|
n = 100 (the original variable changed)
Call by value vs call by reference (using pointers)
| Point | Call by value | Using pointers (reference-like effect) |
|---|---|---|
| What is passed? | A copy of the value | A copy of the variable's address |
| Parameter example | void change(int x) | void change(int *x) |
| Function call | change(n); | change(&n); |
| Statement inside function | x = 100; | *x = 100; |
| Original variable changed? | No | Yes, when dereferenced and written to |
| Actual C argument-passing rule | Pass by value | Pass by value of the address |
Passing &n is not enough to modify n automatically.
The function must dereference the pointer, for example with
*x = 100;. Also, changing x itself would change only
the local copy of the pointer, not the caller's variable or pointer.
Self-check
What will be printed after change(&n) if change() executes *x = 100; and n originally contains 10? Answer: 100, because the function updates the original memory location.
12.17 Local Variables Inside Functions
A variable declared inside a function normally has block scope and can be accessed only within the appropriate block.
void calculate(void)
{
int total = 50;
printf("%d\n", total);
}
The variable total is local to the function.
void calculate(void)
{
int total = 50;
}
int main(void)
{
printf("%d", total); /* Error */
}
total is not visible in main().
12.18 Functions and Global Variables
A variable defined outside functions can have file scope and may be accessible to functions in the same source file according to its declaration and linkage.
#include <stdio.h>
int count = 10;
void display(void)
{
printf("%d\n", count);
}
int main(void)
{
display();
return 0;
}
Global variables can be useful in specific situations, but excessive use of global mutable state can make programs harder to understand and test. Prefer passing required data through function parameters when practical.
12.19 Passing an Array to a Function
Arrays are frequently processed using functions. When an array is passed to a function, the parameter is adjusted to a pointer to its first element.
#include <stdio.h>
void display(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
}
int main(void)
{
int numbers[] = {10, 20, 30, 40};
display(numbers, 4);
return 0;
}
Inside the function, the parameter arr is not a complete
array object. Therefore sizeof(arr) inside the function
does not give the original array size.
12.20 Passing Strings to Functions
A C string is stored in a character array ending with the null character
'\0'.
A string can be passed to a function using a character pointer or an
array parameter.
#include <stdio.h>
void displayString(const char text[])
{
printf("%s\n", text);
}
int main(void)
{
char name[] = "CodeBhavya";
displayString(name);
return 0;
}
The const qualifier communicates that the function does not
intend to modify the characters through that parameter.
12.21 Functions and Pointers — Preview
Pointers allow a function to work with the address of an object. This is how a function can modify a variable belonging to its caller.
#include <stdio.h>
void change(int *x)
{
*x = 100;
}
int main(void)
{
int n = 10;
change(&n);
printf("%d\n", n);
return 0;
}
Here:
&n → address of n
*x → value stored at that address
Pointers will be studied in detail in the dedicated Pointers topic. For now, remember that passing an address gives a function access to the same object.
12.22 Recursion
Recursion occurs when a function calls itself.
void countDown(int n)
{
if (n == 0)
{
return;
}
printf("%d\n", n);
countDown(n - 1);
}
A recursive function normally needs two important parts:
The condition that stops recursion.
The part that calls the function again.
The recursive calls may continue until the program exhausts available stack space, resulting in undefined behavior or abnormal termination.
12.23 Program Tracing — Recursive Function
Consider:
void countDown(int n)
{
if (n == 0)
return;
printf("%d ", n);
countDown(n - 1);
}
Suppose:
countDown(3);
The execution can be visualized as:
countDown(3)
|
| print 3
v
countDown(2)
|
| print 2
v
countDown(1)
|
| print 1
v
countDown(0)
|
| base case
v
return
Output:
3 2 1
When a function calls another function, the current function's execution is paused until the called function returns. For recursion, this creates a chain of active function calls.
12.24 Function Calls and the Call Stack
When a function is called, the program needs to keep track of the function's execution state, parameters and local information. This is commonly represented using the call stack.
main()
|
+--> calculate()
|
+--> square()
|
+--> return
|
+--> return
|
+--> return
TOP
┌──────────────────────┐
│ square() │
├──────────────────────┤
│ calculate() │
├──────────────────────┤
│ main() │
└──────────────────────┘
BOTTOM
When square() returns, its active call is removed and
execution continues in calculate().
12.25 One Function Can Call Another Function
#include <stdio.h>
int square(int n)
{
return n * n;
}
int doubleValue(int n)
{
return 2 * n;
}
int main(void)
{
int value = square(doubleValue(3));
printf("%d\n", value);
return 0;
}
Trace the calls from the inside:
doubleValue(3)
↓
6
square(6)
↓
36
value = 36
For nested function calls, identify which function must produce a value first.
Draw the call chain when the expression looks complicated.
12.26 Designing Good Functions
A good function generally has a clear responsibility.
| Less Clear | Better Decomposition |
|---|---|
One huge main() |
readInput() |
| Mixed calculation and display | calculateTotal() |
| Repeated validation logic | isValid() |
| Repeated searching logic | findMaximum() |
Input
↓
Validation
↓
Calculation
↓
Output
Each responsibility can potentially become a separate function.
12.27 Common Mistakes
1. Calling a function with the wrong number of arguments
int add(int a, int b);
add(10); /* Wrong */
add(10, 20); /* Correct */
2. Forgetting the return statement
int square(int n)
{
n * n; /* Does not return the result */
}
Correct:
int square(int n)
{
return n * n;
}
3. Returning a value from a void function
void display(void)
{
return 10; /* Wrong */
}
4. Using a local variable outside its scope
void test(void)
{
int x = 10;
}
int main(void)
{
printf("%d", x); /* Wrong */
}
5. Infinite recursion
void test(void)
{
test();
}
There is no terminating condition.
6. Modifying a variable incorrectly through a value parameter
void change(int x)
{
x = 100;
}
This does not modify the caller's ordinary variable.
12.28 Common Confusions
Function declaration vs function call
int add(int, int); /* declaration */
add(10, 20); /* call */
Parameter vs argument
int add(int a, int b)
{
return a + b;
}
add(5, 7);
a and b are parameters.
5 and 7 are arguments.
Return value vs printing
int square(int n)
{
return n * n;
}
Returning a value and printing a value are different operations.
void parameter list
void display(void)
This explicitly means that the function accepts no parameters.
12.29 Complete Program Analysis
#include <stdio.h>
int calculateSquare(int n);
int main(void)
{
int number;
int result;
printf("Enter a number: ");
scanf("%d", &number);
result = calculateSquare(number);
printf("Square = %d\n", result);
return 0;
}
int calculateSquare(int n)
{
return n * n;
}
Execution flow
1. Program starts
↓
2. main() begins
↓
3. number is declared
↓
4. Input is read
↓
5. calculateSquare(number) is called
↓
6. value is copied into n
↓
7. n * n is calculated
↓
8. result is returned
↓
9. result receives returned value
↓
10. printf() displays result
↓
11. return 0
↓
12. Program ends
12.30 Important Interview Point: Array Parameter
Consider:
void display(int arr[])
For a function parameter, an array parameter is adjusted to a pointer parameter. Therefore, these forms are equivalent for parameter purposes:
void display(int arr[]);
void display(int *arr);
The array's size is therefore commonly passed separately:
void display(int arr[], int size)
"An array is completely copied when passed to a function."
Better explanation:For a function parameter, an array parameter is adjusted to a pointer to its first element, so the function can access the original array elements.
12.31 Function Pointers and Callback Functions
A function pointer stores the address of a compatible function. Calling a function through a pointer lets the program select behavior at runtime. A callback is a function supplied to another function, often to control processing or comparison.
Complete C program:
#include <stdio.h>
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
int calculate(int a, int b, int (*operation)(int, int))
{
return operation(a, b);
}
int main(void)
{
printf("Add: %d\n", calculate(3, 4, add));
printf("Multiply: %d\n", calculate(3, 4, multiply));
return 0;
}
Expected output:
Add: 7
Multiply: 12
Step-by-step explanation:
- operation is a pointer to a function accepting two int arguments and returning int.
- The first call passes add as the callback.
- The second call passes multiply without changing calculate.
12.32 Variadic Functions and stdarg.h
A variadic function accepts a variable number of arguments, like printf. In C you can process such arguments using va_list, va_start, va_arg and va_end. You must independently know how many arguments were passed and what their types are; there is no built-in argument count.
Complete C program:
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...)
{
va_list args;
int total = 0;
va_start(args, count);
for (int i = 0; i < count; ++i)
total += va_arg(args, int);
va_end(args);
return total;
}
int main(void)
{
printf("Sum = %d\n", sum(3, 4, 5, 6));
return 0;
}
Expected output:
Sum = 15
Step-by-step explanation:
- The first argument announces that three integer arguments follow.
- va_start initializes iteration over the unnamed arguments.
- Each va_arg(args, int) retrieves one int; va_end completes processing.
12.33 Quick Revision
📌 Prototype → Function declaration.
📌 Parameters → Variables in function definition.
📌 Arguments → Actual values passed during the call.
📌 return → Sends a value back.
📌 void → No return value.
📌 Recursion → Function calling itself.
📌 Local variable → Limited to its scope.
📌 Global variable → Declared outside functions.
📌 static local variable → Retains its value between calls.
🎬 Functions — Function Call Flow
Follow how control moves from main() to a function and back to the caller.
🎬 Function Call Visualizer
The active stage changes as control enters the function, processes data, returns, and resumes in main().
🔎 Program Tracing — Functions
Trace a complete function call, parameter passing, local computation, return value, and resumption in main().
—
12.34 Quick MCQs
Select an answer first, then click Check Answer. A correct choice becomes green. If the answer is wrong, your choice becomes red and the correct option becomes green. The explanation appears below.
A function is a named, reusable block of code designed to perform a specific task.
The return type void indicates that the function does not return a value.
Recursion occurs when a function directly or indirectly calls itself.
A base case provides the stopping condition that prevents recursive calls from continuing forever.
return ends the current function invocation and can send a value back to the caller.
For ordinary scalar parameters, C passes argument values to separate parameter variables. Pointers can be passed when a function needs to modify data through an address.
12.35 🎯 Practice Problems
Functions become natural when you practice dividing one program into small reusable tasks. Use 💻 Solve It Yourself first, open Hint only when needed, and use Show Program after attempting the problem.
Problem 1: Create a function that prints "Hello World".
Input: No input.
Output: Print "Hello World".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
void printHello(void)
{
printf("Hello World");
}
int main()
{
printHello();
return 0;
}
Problem 2: Create a function to add two integers.
Input: Two integers.
Output: Print their sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
int x, y;
scanf("%d %d", &x, &y);
printf("%d", add(x, y));
return 0;
}
Problem 3: Create a function to subtract the second integer from the first.
Input: Two integers.
Output: Print a - b.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int subtract(int a, int b)
{
return a - b;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("%d", subtract(a, b));
return 0;
}
Problem 4: Create a function to return the maximum of two integers.
Input: Two integers.
Output: Print the larger value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int maximum(int a, int b)
{
if (a > b)
return a;
return b;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("%d", maximum(a, b));
return 0;
}
Problem 5: Check whether an integer is even or odd using a function.
Input: One integer.
Output: Print "Even" or "Odd".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int isEven(int n)
{
return n % 2 == 0;
}
int main()
{
int n;
scanf("%d", &n);
printf("%s", isEven(n) ? "Even" : "Odd");
return 0;
}
Problem 6: Use a function to classify an integer as positive, negative or zero.
Input: One integer.
Output: Print "Positive", "Negative", or "Zero".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int signOf(int n)
{
if (n > 0)
return 1;
if (n < 0)
return -1;
return 0;
}
int main()
{
int n;
int sign;
scanf("%d", &n);
sign = signOf(n);
if (sign > 0)
printf("Positive");
else if (sign < 0)
printf("Negative");
else
printf("Zero");
return 0;
}
Problem 7: Check whether a number is prime using a function.
Input: One integer.
Output: Print "Prime" or "Not Prime".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int isPrime(int n)
{
if (n < 2)
return 0;
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
return 0;
}
return 1;
}
int main()
{
int n;
scanf("%d", &n);
printf("%s", isPrime(n) ? "Prime" : "Not Prime");
return 0;
}
Problem 8: Find the factorial of a non-negative integer using a normal function.
Input: One integer N from 0 to 20.
Output: Print N!.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
unsigned long long factorial(int n)
{
unsigned long long result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
int main()
{
int n;
scanf("%d", &n);
printf("%llu", factorial(n));
return 0;
}
Problem 9: Find the greatest common divisor of two integers using a function.
Input: Two integers.
Output: Print the non-negative GCD.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <stdlib.h>
int gcd(int a, int b)
{
a = abs(a);
b = abs(b);
while (b != 0)
{
int r = a % b;
a = b;
b = r;
}
return a;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("%d", gcd(a, b));
return 0;
}
Problem 10: Find the least common multiple of two integers using functions.
Input: Two integers.
Output: Print the non-negative LCM.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <stdlib.h>
int gcd(int a, int b)
{
a = abs(a);
b = abs(b);
while (b != 0)
{
int r = a % b;
a = b;
b = r;
}
return a;
}
long long lcm(int a, int b)
{
if (a == 0 || b == 0)
return 0;
int g = gcd(a, b);
long long value = (long long)(a / g) * b;
return value < 0 ? -value : value;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("%lld", lcm(a, b));
return 0;
}
Problem 11: Find 1 + 2 + ... + N using recursion.
Input: One non-negative integer N.
Output: Print the sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
long long sumN(int n)
{
if (n <= 0)
return 0;
return n + sumN(n - 1);
}
int main()
{
int n;
scanf("%d", &n);
printf("%lld", sumN(n));
return 0;
}
Problem 12: Find factorial using recursion.
Input: One integer N from 0 to 20.
Output: Print N!.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
unsigned long long factorial(int n)
{
if (n <= 1)
return 1;
return (unsigned long long)n * factorial(n - 1);
}
int main()
{
int n;
scanf("%d", &n);
printf("%llu", factorial(n));
return 0;
}
Problem 13: Find the Nth Fibonacci number recursively, using F0 = 0 and F1 = 1.
Input: One non-negative integer N.
Output: Print F(N).
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
long long fibonacci(int n)
{
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main()
{
int n;
scanf("%d", &n);
printf("%lld", fibonacci(n));
return 0;
}
Problem 14: Pass an integer array to a function and return the sum of its elements.
Input: N followed by N integers.
Output: Print the sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
long long sumArray(int a[], int n)
{
long long sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return sum;
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("%lld", sumArray(a, n));
return 0;
}
Problem 15: Pass an array to a function and return its maximum element.
Input: N greater than 0 followed by N integers.
Output: Print the maximum value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int maxArray(int a[], int n)
{
int maximum = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > maximum)
maximum = a[i];
}
return maximum;
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("%d", maxArray(a, n));
return 0;
}
Problem 16: Pass an array to a function and return its minimum element.
Input: N greater than 0 followed by N integers.
Output: Print the minimum value.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int minArray(int a[], int n)
{
int minimum = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] < minimum)
minimum = a[i];
}
return minimum;
}
int main()
{
int n;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("%d", minArray(a, n));
return 0;
}
Problem 17: Pass a string to a function and print it from that function.
Input: One line of text.
Output: Print the same line.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
void printString(const char text[])
{
printf("%s", text);
}
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
printString(text);
return 0;
}
Problem 18: Check whether a string is a palindrome using a function.
Input: One line of text.
Output: Print "Palindrome" or "Not Palindrome".
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
#include <string.h>
int isPalindrome(const char text[])
{
int left = 0;
int right = (int)strlen(text) - 1;
while (left < right)
{
if (text[left] != text[right])
return 0;
left++;
right--;
}
return 1;
}
int main()
{
char text[200];
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
printf("%s", isPalindrome(text) ? "Palindrome" : "Not Palindrome");
return 0;
}
Problem 19: Swap two integer variables using a function that receives their addresses.
Input: Two integers.
Output: Print the values after swapping.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x, y;
scanf("%d %d", &x, &y);
swap(&x, &y);
printf("%d %d", x, y);
return 0;
}
Problem 20: Create separate functions for addition, subtraction, multiplication and division, then choose the operation using a menu choice.
Input: Choice (1=add, 2=subtract, 3=multiply, 4=divide), followed by two numbers.
Output: Print the calculated result. Division is printed to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
double add(double a, double b)
{
return a + b;
}
double subtract(double a, double b)
{
return a - b;
}
double multiply(double a, double b)
{
return a * b;
}
double divide(double a, double b)
{
return a / b;
}
int main()
{
int choice;
double a, b;
scanf("%d %lf %lf", &choice, &a, &b);
switch (choice)
{
case 1:
printf("%.2f", add(a, b));
break;
case 2:
printf("%.2f", subtract(a, b));
break;
case 3:
printf("%.2f", multiply(a, b));
break;
case 4:
if (b == 0)
printf("Division by zero");
else
printf("%.2f", divide(a, b));
break;
default:
printf("Invalid Choice");
}
return 0;
}
12.36 Key Takeaway
Large Problem → Break into Smaller Problems → Create Functions → Call Functions → Combine Results
Functions are the foundation for writing clean, reusable and modular C programs.
🎤 Functions — Interview Questions
💡 Functions — Placement Tips
- Before writing a function, decide its inputs, task, and return value.
- Use meaningful function names such as
isPrime(),findMax(), andcalculateSum(). - In recursion questions, identify the base case first, then write the smaller recursive subproblem.
- Remember that ordinary scalar arguments are passed by value; use addresses when the original caller data must be modified.
- Keep local variables local unless there is a genuine reason to use broader scope.
- In interviews, explain both the function's logic and the cost of repeated calls, especially for recursive solutions such as naive Fibonacci.
✍️ Functions — Extra Practice Questions
- Write a function to return the sum of digits of an integer.
- Write a recursive function to calculate a raised to the power b.
- Write a function to check whether a number is a perfect number.
- Write a function that counts vowels in a string.
- Write separate functions for reading, transposing, and printing a matrix.
- Write a recursive function to calculate the GCD of two integers.