LearnFrenzy
Sign in Take a free test

C Programming · Topic 4 of 23

Functions

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Coding Techniques

Functions · Study material

Memoization with a static array

Naive recursive Fibonacci recomputes the same values exponentially many times. Caching each result in a static array makes it O(n).

#include <stdio.h>

unsigned long long fib(int n) {
    static unsigned long long memo[94];     /* fib(93) is the largest that fits in 64 bits */
    if (n < 2)
        return (unsigned long long) n;
    if (memo[n] == 0)
        memo[n] = fib(n - 1) + fib(n - 2);  /* each value is computed once */
    return memo[n];
}

int main(void) {
    printf("fib(10) = %llu\nfib(90) = %llu\n", fib(10), fib(90));
    return 0;
}

Output

fib(10) = 55
fib(90) = 2880067194370816120

Turning recursion into a loop

When the recursive call is the last thing a function does (a tail call), the same logic fits in a loop that uses no extra stack.

#include <stdio.h>

int gcd_rec(int a, int b)  { return b == 0 ? a : gcd_rec(b, a % b); }   /* tail call */

int gcd_loop(int a, int b) {                                             /* same logic, no stack growth */
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

int main(void) {
    printf("%d %d\n", gcd_rec(84, 36), gcd_loop(84, 36));
    return 0;
}

Output

12 12

Returning several values in a struct

A function can return a whole struct by value – often cleaner than three output pointers.

#include <stdio.h>

struct stats {
    int min, max;
    double mean;
};

struct stats describe(const int *a, int n) {        /* several results in one return value */
    struct stats s = {a[0], a[0], 0.0};
    long sum = 0;
    for (int i = 0; i < n; i++) {
        if (a[i] < s.min) s.min = a[i];
        if (a[i] > s.max) s.max = a[i];
        sum += a[i];
    }
    s.mean = (double) sum / n;
    return s;
}

int main(void) {
    int a[] = {4, 8, 15, 16, 23, 42};
    struct stats s = describe(a, 6);
    printf("min %d, max %d, mean %.2f\n", s.min, s.max, s.mean);
    return 0;
}

Output

min 4, max 42, mean 18.00

Status return + output parameter

For operations that can fail, return a status and write the result through a pointer. Mark the status [[nodiscard]] in C23 so callers cannot silently ignore it.

[[nodiscard]] bool parse_age(const char *text, int *age);   /* C23 */

int age;
if (!parse_age(input, &age)) {
    puts("Please enter a valid age.");
}

Good function habits

  • One job per function, with a name that says what it returns or does.
  • Prototype every function; write (void) for no parameters.
  • Mark helper functions static so they stay private to the file.
  • Use const for pointer parameters the function only reads.
  • Never depend on the evaluation order of arguments: f(i++, i) is a bug.
  • Compile with -Wall -Wextra: missing returns and implicit declarations are caught at once.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links