c

examples

examples.c🔧
/**
 * @file examples.c
 * @brief Function Basics Examples
 * 
 * This file demonstrates functions in C.
 * 
 * Compile: gcc -Wall examples.c -o examples -lm
 * Run: ./examples
 */

#include <stdio.h>
#include <math.h>

/* ============================================================
 * FUNCTION PROTOTYPES (Declarations)
 * ============================================================ */
void greet(void);
void printLine(int length, char ch);
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
float divide(int a, int b);
int square(int n);
int cube(int n);
int maximum(int a, int b);
int minimum(int a, int b);
int isEven(int n);
int isPrime(int n);
int factorial(int n);
int sumOfDigits(int n);
void printMultTable(int n);

/* ============================================================
 * EXAMPLE 1: SIMPLE FUNCTION - NO PARAMS, NO RETURN
 * ============================================================ */
void greet(void) {
    printf("Hello! Welcome to C programming.\n");
}

void example_simple_function() {
    printf("\n=== Example 1: Simple Function ===\n");
    
    greet();  // Call the function
    greet();  // Call again
}

/* ============================================================
 * EXAMPLE 2: FUNCTION WITH PARAMETERS
 * ============================================================ */
void printLine(int length, char ch) {
    for (int i = 0; i < length; i++) {
        printf("%c", ch);
    }
    printf("\n");
}

void example_function_params() {
    printf("\n=== Example 2: Function with Parameters ===\n");
    
    printLine(20, '-');
    printLine(10, '*');
    printLine(15, '=');
}

/* ============================================================
 * EXAMPLE 3: FUNCTION WITH RETURN VALUE
 * ============================================================ */
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;
}

float divide(int a, int b) {
    if (b == 0) {
        printf("Error: Division by zero!\n");
        return 0.0f;
    }
    return (float)a / b;
}

void example_return_values() {
    printf("\n=== Example 3: Functions with Return Values ===\n");
    
    int x = 15, y = 4;
    
    printf("%d + %d = %d\n", x, y, add(x, y));
    printf("%d - %d = %d\n", x, y, subtract(x, y));
    printf("%d * %d = %d\n", x, y, multiply(x, y));
    printf("%d / %d = %.2f\n", x, y, divide(x, y));
}

/* ============================================================
 * EXAMPLE 4: MATHEMATICAL FUNCTIONS
 * ============================================================ */
int square(int n) {
    return n * n;
}

int cube(int n) {
    return n * n * n;
}

void example_math_functions() {
    printf("\n=== Example 4: Mathematical Functions ===\n");
    
    for (int i = 1; i <= 5; i++) {
        printf("n=%d: square=%d, cube=%d\n", i, square(i), cube(i));
    }
    
    // Using standard library math functions
    printf("\nUsing math.h:\n");
    printf("sqrt(16) = %.2f\n", sqrt(16));
    printf("pow(2, 10) = %.0f\n", pow(2, 10));
}

/* ============================================================
 * EXAMPLE 5: COMPARISON FUNCTIONS
 * ============================================================ */
int maximum(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}

int minimum(int a, int b) {
    return (a < b) ? a : b;  // Using ternary operator
}

void example_comparison() {
    printf("\n=== Example 5: Comparison Functions ===\n");
    
    int a = 25, b = 17;
    
    printf("max(%d, %d) = %d\n", a, b, maximum(a, b));
    printf("min(%d, %d) = %d\n", a, b, minimum(a, b));
    
    // Finding max of 3 numbers using nested calls
    int c = 30;
    int max3 = maximum(maximum(a, b), c);
    printf("max(%d, %d, %d) = %d\n", a, b, c, max3);
}

/* ============================================================
 * EXAMPLE 6: BOOLEAN-LIKE FUNCTIONS
 * ============================================================ */
int isEven(int n) {
    return n % 2 == 0;  // Returns 1 (true) or 0 (false)
}

int isPrime(int n) {
    if (n <= 1) return 0;
    if (n <= 3) return 1;
    if (n % 2 == 0) return 0;
    
    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0) return 0;
    }
    return 1;
}

void example_boolean_functions() {
    printf("\n=== Example 6: Boolean-like Functions ===\n");
    
    printf("Even check: ");
    for (int i = 1; i <= 10; i++) {
        printf("%d:%s ", i, isEven(i) ? "E" : "O");
    }
    printf("\n");
    
    printf("Prime check (1-20): ");
    for (int i = 1; i <= 20; i++) {
        if (isPrime(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
}

/* ============================================================
 * EXAMPLE 7: FACTORIAL FUNCTION
 * ============================================================ */
int factorial(int n) {
    if (n < 0) return -1;  // Error case
    if (n <= 1) return 1;  // Base case
    
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

void example_factorial() {
    printf("\n=== Example 7: Factorial Function ===\n");
    
    for (int i = 0; i <= 10; i++) {
        printf("%2d! = %d\n", i, factorial(i));
    }
}

/* ============================================================
 * EXAMPLE 8: DIGIT PROCESSING
 * ============================================================ */
int sumOfDigits(int n) {
    int sum = 0;
    if (n < 0) n = -n;  // Handle negative
    
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int countDigits(int n) {
    if (n == 0) return 1;
    if (n < 0) n = -n;
    
    int count = 0;
    while (n > 0) {
        count++;
        n /= 10;
    }
    return count;
}

int reverseNumber(int n) {
    int reversed = 0;
    int sign = (n < 0) ? -1 : 1;
    if (n < 0) n = -n;
    
    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }
    return reversed * sign;
}

void example_digit_functions() {
    printf("\n=== Example 8: Digit Processing ===\n");
    
    int num = 12345;
    printf("Number: %d\n", num);
    printf("Sum of digits: %d\n", sumOfDigits(num));
    printf("Number of digits: %d\n", countDigits(num));
    printf("Reversed: %d\n", reverseNumber(num));
}

/* ============================================================
 * EXAMPLE 9: FUNCTION THAT PRINTS (VOID RETURN)
 * ============================================================ */
void printMultTable(int n) {
    printf("\nMultiplication table for %d:\n", n);
    for (int i = 1; i <= 10; i++) {
        printf("%d x %2d = %2d\n", n, i, n * i);
    }
}

void example_void_function() {
    printf("\n=== Example 9: Void Function ===\n");
    
    printMultTable(7);
}

/* ============================================================
 * EXAMPLE 10: FUNCTION USING OTHER FUNCTIONS
 * ============================================================ */
int isPerfectSquare(int n) {
    if (n < 0) return 0;
    int root = (int)sqrt(n);
    return root * root == n;
}

void printPerfectSquares(int limit) {
    printf("Perfect squares up to %d: ", limit);
    for (int i = 0; i <= limit; i++) {
        if (isPerfectSquare(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
}

void example_function_composition() {
    printf("\n=== Example 10: Function Composition ===\n");
    
    printPerfectSquares(100);
}

/* ============================================================
 * EXAMPLE 11: PASS BY VALUE DEMONSTRATION
 * ============================================================ */
void tryToModify(int n) {
    printf("  Inside function (before): n = %d\n", n);
    n = n * 2;  // Modifies local copy only!
    printf("  Inside function (after): n = %d\n", n);
}

void example_pass_by_value() {
    printf("\n=== Example 11: Pass by Value ===\n");
    
    int x = 10;
    printf("Before function call: x = %d\n", x);
    tryToModify(x);
    printf("After function call: x = %d\n", x);
    printf("(x unchanged because C uses pass-by-value)\n");
}

/* ============================================================
 * EXAMPLE 12: MULTIPLE RETURN STATEMENTS
 * ============================================================ */
char getGrade(int score) {
    if (score >= 90) return 'A';
    if (score >= 80) return 'B';
    if (score >= 70) return 'C';
    if (score >= 60) return 'D';
    return 'F';
}

void example_multiple_returns() {
    printf("\n=== Example 12: Multiple Return Statements ===\n");
    
    int scores[] = {95, 82, 75, 65, 55};
    int n = sizeof(scores) / sizeof(scores[0]);
    
    for (int i = 0; i < n; i++) {
        printf("Score %d -> Grade %c\n", scores[i], getGrade(scores[i]));
    }
}

/* ============================================================
 * EXAMPLE 13: CALCULATOR USING FUNCTIONS
 * ============================================================ */
float calculate(int a, int b, char op) {
    switch (op) {
        case '+': return add(a, b);
        case '-': return subtract(a, b);
        case '*': return multiply(a, b);
        case '/': return divide(a, b);
        default:
            printf("Unknown operator: %c\n", op);
            return 0;
    }
}

void example_calculator() {
    printf("\n=== Example 13: Calculator ===\n");
    
    int a = 20, b = 5;
    char ops[] = {'+', '-', '*', '/'};
    
    for (int i = 0; i < 4; i++) {
        printf("%d %c %d = %.2f\n", a, ops[i], b, calculate(a, b, ops[i]));
    }
}

/* ============================================================
 * EXAMPLE 14: GCD AND LCM
 * ============================================================ */
int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int lcm(int a, int b) {
    return (a / gcd(a, b)) * b;  // Avoid overflow
}

void example_gcd_lcm() {
    printf("\n=== Example 14: GCD and LCM ===\n");
    
    int pairs[][2] = {{12, 18}, {24, 36}, {17, 23}};
    int n = sizeof(pairs) / sizeof(pairs[0]);
    
    for (int i = 0; i < n; i++) {
        int a = pairs[i][0], b = pairs[i][1];
        printf("GCD(%d, %d) = %d, LCM(%d, %d) = %d\n", 
               a, b, gcd(a, b), a, b, lcm(a, b));
    }
}

/* ============================================================
 * MAIN FUNCTION
 * ============================================================ */
int main() {
    printf("╔════════════════════════════════════════════════╗\n");
    printf("║    FUNCTION BASICS - EXAMPLES                  ║\n");
    printf("║    Functions in C Programming                  ║\n");
    printf("╚════════════════════════════════════════════════╝\n");
    
    example_simple_function();
    example_function_params();
    example_return_values();
    example_math_functions();
    example_comparison();
    example_boolean_functions();
    example_factorial();
    example_digit_functions();
    example_void_function();
    example_function_composition();
    example_pass_by_value();
    example_multiple_returns();
    example_calculator();
    example_gcd_lcm();
    
    printf("\n=== All Examples Completed! ===\n");
    
    return 0;
}
Examples - C Programming Tutorial | DeepML