🟡 Intermediate  ·  Lesson 17

Functions in C

Functions

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.

Function क्या है?

Function code का एक self-contained block है जो एक specific task perform करता है। एक ही code बार-बार लिखने की बजाय, उसे function में एक बार लिखें और जब चाहें call करें।

💡 Functions क्यों use करें?
  • Reusability — एक बार लिखो, कहीं भी use करो
  • Modularity — बड़े program को छोटे टुकड़ों में तोड़ो
  • Readability — Code clean और समझने में आसान
  • Debugging — छोटे functions में bugs ढूंढना आसान

Functions के प्रकार

प्रकारDefinitionExample
Library FunctionsC libraries में pre-definedprintf(), scanf(), sqrt()
User-defined FunctionsProgrammer द्वारा बनाई गईadd(), areaCircle()

Function Define करना

Structure
return_type function_name(parameters) {
    // Function का काम
    return value;  // void नहीं है तो
}

Function Call करना

C Language
#include <stdio.h>

void namaste() {
    printf("Namaste CodeKaFunda!\\n");
}

int jodo(int a, int b) {
    return a + b;
}

int main() {
    namaste();                            // Call — no return
    int s = jodo(10, 20);              // Call — return value store
    printf("Jod = %d\\n", s);
    return 0;
}
Namaste CodeKaFunda! Jod = 30

Return Values

C Language
int varg(int a, int b)   { return (a > b) ? a : b; }
int varg_teen(int a, int b, int c) { return (a>b && a>c) ? a : (b>c ? b : c); }
int isPrime(int n) {
    if (n <= 1) return 0;
    for(int i = 2; i*i <= n; i++) if(n%i == 0) return 0;
    return 1;
}

Programs

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

float kshetrafal(float r) { return PI * r * r; }

int main() {
    float r;
    scanf("%f", &r);
    printf("Kshetrafal = %.2f\\n", kshetrafal(r));
    return 0;
}

सारांश

  • Function एक reusable code block है जो specific task करता है
  • Syntax: return_type naam(parameters) { body }
  • void = function कुछ return नहीं करता
  • return statement value वापस caller को भेजता है
  • Local variables function के अंदर ही exist करते हैं
🏋️ Practice

Functions लिखें: (1) isPrime(n) — prime check (2) power(base, exp) — base^exp (3) pahada(n) — multiplication table print (4) celsiusToFahrenheit(c) — temperature convert करें।

← Back to C Tutorial