🧩 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.

Core idea:

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.

Function name

greet

Return type

void

Parameters

void — no parameters

Function body

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.

Without functions:
main()
{
    input code
    calculation code
    validation code
    display code
    another calculation
    another validation
    another display
}
With functions:
main()
{
    readData();
    calculateResult();
    validateResult();
    displayResult();
}
Reusability

Write logic once and call it multiple times.

Readability

Function names explain what different parts of a program do.

Testing

Individual functions can be tested separately.

Maintenance

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 int parameters
  • will be defined somewhere in the program
Remember:

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 vs Definition
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
Important:

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);
Do not confuse these:
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
Important:

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;
}
Style 1

Prototype first, definition later.

Style 2

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).

CategoryArguments?Returns a value?Example declaration
1. No arguments, no return valueNoNovoid greet(void)
2. Arguments, no return valueYesNovoid printSquare(int number)
3. No arguments, returns a valueNoYesint getNumber(void)
4. Arguments and returns a valueYesYesint 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:

  1. Execution begins in main().
  2. greet() is called without arguments.
  3. greet() prints the message.
  4. Control returns to main(); no result is returned by greet().
Remember: 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:

  1. main() calls printSquare(5).
  2. The argument 5 is copied into the parameter number.
  3. printSquare() calculates 5 * 5 and prints 25.
  4. The function finishes and control returns to main(), without returning a value.
Remember: An argument passes input into the function. Even though the square appears on the screen, the 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:

  1. main() calls getNumber() without arguments.
  2. getNumber() executes return 42;.
  3. The returned integer is stored in value.
  4. main() prints Number = 42.
Remember: 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:

  1. main() calls add(10, 20).
  2. Parameters a and b receive copies of 10 and 20.
  3. return a + b; sends 30 to the caller.
  4. sum stores 30 and main() prints the result.
Remember: 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

HeaderInput to functionReturned resultCategory
void message(void)NoneNone1
void display(int n)int nNone2
float getRate(void)Nonefloat3
double average(int x, int y)int x, int ydouble4
Common confusion: printing is not returning

printf("%d", 10); displays 10. The expression return 10; sends 10 back to the caller. They serve different purposes.

Another confusion: void appears twice

In void greet(void), the first void means no return value; the void inside parentheses explicitly means no parameters.

Placement memory trick:

Ask two questions:

  1. Does the function receive data?
  2. 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.

  1. void show(int age) — arguments, but no return value: Category 2.
  2. int readChoice(void) — no arguments, returns a value: Category 3.
  3. float area(float radius) — arguments and returns a value: Category 4.
  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
Important:

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.

Important C language fact:

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:

  1. main() creates a variable n with value 10.
  2. change(&n) passes the address of n to the function.
  3. The pointer parameter x stores a copy of that address.
  4. *x = 100; writes 100 to the original variable's memory location.
  5. When the function finishes, n in main() is now 100.
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)

PointCall by valueUsing pointers (reference-like effect)
What is passed?A copy of the valueA copy of the variable's address
Parameter examplevoid change(int x)void change(int *x)
Function callchange(n);change(&n);
Statement inside functionx = 100;*x = 100;
Original variable changed?NoYes, when dereferenced and written to
Actual C argument-passing rulePass by valuePass by value of the address
Common confusion:

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.

Common mistake:
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;
}
Important design note:

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;
}
Why pass the size separately?

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
Do not worry about pointers yet.

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:

Base case

The condition that stops recursion.

Recursive case

The part that calls the function again.

Without a proper base case:

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
Important tracing idea

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
Tracing tip

For nested function calls, identify which function must produce a value first.

Placement tip

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()
Think in responsibilities:
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)
Do not say:

"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:

  1. operation is a pointer to a function accepting two int arguments and returning int.
  2. The first call passes add as the callback.
  3. The second call passes multiply without changing calculate.
Remember: Function pointers are different from pointers to ordinary data. Their signatures must be compatible; unsafe casts are not a substitute.

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:

  1. The first argument announces that three integer arguments follow.
  2. va_start initializes iteration over the unnamed arguments.
  3. Each va_arg(args, int) retrieves one int; va_end completes processing.
Remember: Default argument promotions apply: float becomes double and narrow integer types become int (or unsigned int). A mismatched va_arg type can be undefined behavior.

12.33 Quick Revision

📌 Function → Reusable block of code.

📌 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.
INTERACTIVE LEARNING

🎬 Functions — Function Call Flow

Follow how control moves from main() to a function and back to the caller.

PROGRAM TRACING

🔎 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.

1. What is a function?
2. Which keyword indicates that a function returns no value?
3. What is recursion?
4. What should recursive functions normally have to stop recursion?
5. Which keyword is used to send a value back from a function?
6. Ordinary C function arguments are generally passed:
PRACTICE

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.

📈 Functions Practice Progress
Solved 0 / 20
Completed with Solution 0
Total Score 0 / 400
Completion 0%
A problem counts as Solved when all test cases pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Print Hello World Using a Function

Problem 1: Create a function that prints "Hello World".

Input: No input.

Output: Print "Hello World".

2. Add Two Numbers Using a Function

Problem 2: Create a function to add two integers.

Input: Two integers.

Output: Print their sum.

3. Subtract Two Numbers Using a Function

Problem 3: Create a function to subtract the second integer from the first.

Input: Two integers.

Output: Print a - b.

4. Maximum of Two Numbers

Problem 4: Create a function to return the maximum of two integers.

Input: Two integers.

Output: Print the larger value.

5. Even or Odd Using a Function

Problem 5: Check whether an integer is even or odd using a function.

Input: One integer.

Output: Print "Even" or "Odd".

6. Positive, Negative or Zero

Problem 6: Use a function to classify an integer as positive, negative or zero.

Input: One integer.

Output: Print "Positive", "Negative", or "Zero".

7. Prime Number Using a Function

Problem 7: Check whether a number is prime using a function.

Input: One integer.

Output: Print "Prime" or "Not Prime".

8. Factorial Using a Function

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!.

9. GCD Using a Function

Problem 9: Find the greatest common divisor of two integers using a function.

Input: Two integers.

Output: Print the non-negative GCD.

10. LCM Using a Function

Problem 10: Find the least common multiple of two integers using functions.

Input: Two integers.

Output: Print the non-negative LCM.

11. Recursive Sum of First N Natural Numbers

Problem 11: Find 1 + 2 + ... + N using recursion.

Input: One non-negative integer N.

Output: Print the sum.

12. Recursive Factorial

Problem 12: Find factorial using recursion.

Input: One integer N from 0 to 20.

Output: Print N!.

13. Nth Fibonacci Number Using Recursion

Problem 13: Find the Nth Fibonacci number recursively, using F0 = 0 and F1 = 1.

Input: One non-negative integer N.

Output: Print F(N).

14. Sum of an Array Using a Function

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.

15. Maximum Array Element Using a Function

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.

16. Minimum Array Element Using a Function

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.

17. Pass a String to a Function

Problem 17: Pass a string to a function and print it from that function.

Input: One line of text.

Output: Print the same line.

18. Palindrome String Using a Function

Problem 18: Check whether a string is a palindrome using a function.

Input: One line of text.

Output: Print "Palindrome" or "Not Palindrome".

19. Swap Two Numbers Using a Function and Pointers

Problem 19: Swap two integer variables using a function that receives their addresses.

Input: Two integers.

Output: Print the values after swapping.

20. Menu-Driven Calculator with Separate Functions

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.

12.36 Key Takeaway

🎯 The most important idea:

Large Problem → Break into Smaller Problems → Create Functions → Call Functions → Combine Results

Functions are the foundation for writing clean, reusable and modular C programs.
INTERVIEW PREPARATION

🎤 Functions — Interview Questions

1. What is the difference between a function declaration, definition, and call?
2. What is the difference between parameters and arguments?
3. What does pass by value mean in C?
4. Why are pointers used when a function must modify a caller variable?
5. What is recursion and what is a base case?
6. What is the difference between local and global variables?
7. What is a static local variable?
8. Why are small single-purpose functions useful?
PLACEMENT TIPS

💡 Functions — Placement Tips

  • Before writing a function, decide its inputs, task, and return value.
  • Use meaningful function names such as isPrime(), findMax(), and calculateSum().
  • 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.
EXTRA PRACTICE

✍️ Functions — Extra Practice Questions

  1. Write a function to return the sum of digits of an integer.
  2. Write a recursive function to calculate a raised to the power b.
  3. Write a function to check whether a number is a perfect number.
  4. Write a function that counts vowels in a string.
  5. Write separate functions for reading, transposing, and printing a matrix.
  6. Write a recursive function to calculate the GCD of two integers.
← Previous Topic: Strings Next Topic: Pointers →