🟡 Intermediate  ·  Lesson 17

Functions in C

What is a Function?

A function is a self-contained block of code that performs a specific task. Instead of writing the same code multiple times, you write it once in a function and call it whenever needed.

💡 Why Use Functions?
  • Reusability — Write once, use anywhere
  • Modularity — Break big program into small, manageable pieces
  • Readability — Code becomes cleaner and easier to understand
  • Debugging — Easier to find and fix bugs in small functions
  • Maintenance — Change logic in one place, it's fixed everywhere

You already know one function: main()! Every C program's execution starts there. printf() and scanf() are also functions — defined in stdio.h.

Types of Functions

TypeDefinitionExample
Library FunctionsPre-defined in C librariesprintf(), scanf(), sqrt(), strlen()
User-defined FunctionsCreated by the programmeradd(), calculateArea(), printMenu()

In this lesson we focus on user-defined functions.

Defining a Function

Function Structure
return_type function_name(parameter1, parameter2, ...) {
    // Function body
    return value;  // if return_type is not void
}

// Examples:
void greet()              // No parameters, no return
int  add(int a, int b)   // Two int params, returns int
float area(float r)       // One float param, returns float

Example 1: Simple void Function (No Return)

C Language
#include <stdio.h>

void printLine() {               // Function definition
    printf("====================\\n");
}

void greet(char *name) {         // Function with parameter
    printf("Hello, %s!\\n", name);
}

int main() {
    printLine();                  // Calling the function
    greet("Gagan");               // Call with argument
    greet("Rahul");
    printLine();
    return 0;
}
==================== Hello, Gagan! Hello, Rahul! ====================

Calling a Function

C Language
greet();           // No arguments
greet("Alice");    // With argument (must match parameter type)
int s = add(5, 3); // Store return value
printf("%d", add(10, 20)); // Use return value directly

Function Prototype (Declaration)

If you define a function after main(), you must declare its prototype before it:

C Language
#include <stdio.h>

int add(int, int);  // Prototype: tells compiler about the function

int main() {
    printf("Sum = %d\\n", add(5, 3));
    return 0;
}

int add(int a, int b) {  // Actual definition
    return a + b;
}

Return Values

C Language – Functions with Return
#include <stdio.h>

int add(int a, int b)      { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int square(int n)           { return n * n; }
int max(int a, int b)       { return (a > b) ? a : b; }
int isEven(int n)           { return (n % 2 == 0); }

int main() {
    printf("add(10, 5)       = %d\\n", add(10, 5));
    printf("square(7)        = %d\\n", square(7));
    printf("max(15, 22)      = %d\\n", max(15, 22));
    printf("isEven(8)        = %d\\n", isEven(8));
    return 0;
}
add(10, 5) = 15 square(7) = 49 max(15, 22) = 22 isEven(8) = 1

Complete Programs

Area of Circle

C Language
#include <stdio.h>
#define PI 3.14159

float areaCircle(float r) {
    return PI * r * r;
}
float circumference(float r) {
    return 2 * PI * r;
}

int main() {
    float r;
    printf("Enter radius: ");
    scanf("%f", &r);
    printf("Area          = %.2f\\n", areaCircle(r));
    printf("Circumference = %.2f\\n", circumference(r));
    return 0;
}
Enter radius: 7 Area = 153.94 Circumference = 43.98

Variable Scope in Functions

Variables declared inside a function are local — they only exist within that function and are destroyed when the function returns.

C Language
int x = 100;  // Global variable: accessible everywhere

void demo() {
    int y = 50;  // Local variable: only in demo()
    printf("x = %d, y = %d\\n", x, y);
}

int main() {
    demo();
    printf("x = %d\\n", x);
    // printf("y = %d\\n", y);  // ERROR: y not accessible here
    return 0;
}

Summary

  • A function is a reusable block of code that performs a specific task
  • Syntax: return_type name(parameters) { body }
  • void return type = function returns nothing
  • Use return to send a value back to the caller
  • Prototype/declaration needed if function is defined after main()
  • Local variables exist only inside their function
  • Arguments are values passed to function parameters
🏋️ Practice

Write functions: (1) isPrime(n) returns 1 if prime (2) power(base, exp) calculates base^exp (3) printTable(n) prints multiplication table (4) celsiusToFahrenheit(c) converts temperature.

Frequently Asked Questions

What is a function in C?
A function is a named block of code that performs a specific task and can be called whenever needed. It helps break a program into smaller, reusable pieces, so instead of repeating code you write it once in a function and call it by name.
What are the parts of a function in C?
A function has a return type, a name, a parameter list in parentheses, and a body in braces. For example in int add(int a, int b), int is the return type, add is the name, and a and b are parameters.
What is a function prototype in C?
A prototype declares a function's name, return type and parameters before it is used, so the compiler knows how to call it. It usually appears near the top of the file or in a header, and the full definition can come later.
What is the difference between a library and a user-defined function?
Library functions such as printf come ready-made with C and are used by including a header. User-defined functions are the ones you write yourself for your own tasks. Both are called the same way, by name with arguments in parentheses.
Why are functions important in programming?
Functions make code reusable, easier to read, and easier to test, because each one handles a single job. They reduce repetition and let large programs be built from small, well-named pieces that can be understood and fixed independently.
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.