c

examples

examples.c🔧
/*
 * ============================================================================
 * STRUCTURE OF A C PROGRAM - EXAMPLES
 * ============================================================================
 * This file demonstrates the proper structure and organization of C programs.
 * 
 * Compile: gcc examples.c -o examples
 * Run: ./examples
 * ============================================================================
 */

/* ============================================================================
 * SECTION 1: PREPROCESSOR DIRECTIVES
 * ============================================================================
 * These lines are processed before compilation.
 * They include libraries and define constants.
 */

// Standard library includes (angle brackets for system headers)
#include <stdio.h>      // For printf, scanf
#include <stdlib.h>     // For malloc, free, exit
#include <string.h>     // For string functions
#include <math.h>       // For mathematical functions

// Constant definitions using #define
#define PROGRAM_NAME "Structure Demo"
#define VERSION 1.0
#define MAX_NAME_LENGTH 50
#define PI 3.14159265359

// Macro definitions (like small inline functions)
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

// Conditional compilation
#define DEBUG_MODE 1    // Set to 0 to disable debug messages

/* ============================================================================
 * SECTION 2: GLOBAL DECLARATIONS
 * ============================================================================
 * Variables and function prototypes accessible throughout the program.
 */

// Global variables (use sparingly!)
int globalCounter = 0;
const char* author = "C Learner";

// Structure definitions
struct Person {
    char name[MAX_NAME_LENGTH];
    int age;
    float height;
};

// Type definitions
typedef unsigned int uint;
typedef struct Person Person;

// Enumeration
enum Color { RED, GREEN, BLUE, YELLOW };

// Function prototypes (declarations)
void demonstratePreprocessor();
void demonstrateGlobalDeclarations();
void demonstrateMainStructure();
void demonstrateFunctions();
void helperFunction(int value);
int calculate(int x, int y, char operation);
void printPerson(Person p);

/* ============================================================================
 * SECTION 3: MAIN FUNCTION
 * ============================================================================
 * The entry point of the program. Execution begins here.
 */

int main() {
    /*
     * Local Variable Declarations
     * --------------------------
     * Variables declared inside a function are local to that function.
     * They should be declared at the beginning of the block (good practice).
     */
    int choice = 0;
    char continueProgram = 'y';
    
    /*
     * Program Header
     * --------------
     * Display program information at startup.
     */
    printf("╔════════════════════════════════════════════════╗\n");
    printf("║    %s v%.1f                  ║\n", PROGRAM_NAME, VERSION);
    printf("║    Demonstrating C Program Structure           ║\n");
    printf("╚════════════════════════════════════════════════╝\n");
    
    // Debug message (only if DEBUG_MODE is enabled)
    #if DEBUG_MODE
        printf("\n[DEBUG] Debug mode is enabled\n");
    #endif
    
    /*
     * Main Program Logic
     * ------------------
     * Call different demonstration functions.
     */
    
    printf("\n--- Available Demonstrations ---\n");
    printf("1. Preprocessor Directives\n");
    printf("2. Global Declarations\n");
    printf("3. Main Function Structure\n");
    printf("4. User-Defined Functions\n");
    printf("5. Run All\n");
    
    printf("\nRunning all demonstrations...\n");
    
    demonstratePreprocessor();
    demonstrateGlobalDeclarations();
    demonstrateMainStructure();
    demonstrateFunctions();
    
    /*
     * Return Statement
     * ----------------
     * Returning 0 indicates successful program execution.
     * Non-zero values indicate errors.
     */
    printf("\n=== Program completed successfully ===\n");
    return 0;  // EXIT_SUCCESS can also be used
}

/* ============================================================================
 * SECTION 4: USER-DEFINED FUNCTIONS
 * ============================================================================
 * Functions that perform specific tasks. Defined after main() but
 * declared (prototyped) before main().
 */

/*
 * Demonstrate Preprocessor Directives
 * -----------------------------------
 * Shows how #define and #include work.
 */
void demonstratePreprocessor() {
    printf("\n=== 1. Preprocessor Directives ===\n");
    
    // Using defined constants
    printf("Program Name: %s\n", PROGRAM_NAME);
    printf("Version: %.1f\n", VERSION);
    printf("Max Name Length: %d\n", MAX_NAME_LENGTH);
    printf("PI value: %.10f\n", PI);
    
    // Using macros
    int num = 5;
    printf("\nMacro SQUARE(%d) = %d\n", num, SQUARE(num));
    printf("Macro MAX(10, 20) = %d\n", MAX(10, 20));
    printf("Macro MIN(10, 20) = %d\n", MIN(10, 20));
    
    // Using library functions (from included headers)
    printf("\nUsing math.h: sqrt(16) = %.2f\n", sqrt(16));
    printf("Using string.h: strlen(\"Hello\") = %lu\n", strlen("Hello"));
}

/*
 * Demonstrate Global Declarations
 * -------------------------------
 * Shows global variables, structures, and enums.
 */
void demonstrateGlobalDeclarations() {
    printf("\n=== 2. Global Declarations ===\n");
    
    // Accessing global variable
    globalCounter++;
    printf("Global counter: %d\n", globalCounter);
    printf("Author: %s\n", author);
    
    // Using structure
    Person person1;
    strcpy(person1.name, "Alice");
    person1.age = 25;
    person1.height = 5.6;
    
    printf("\nPerson Structure:\n");
    printPerson(person1);
    
    // Using typedef
    uint positiveNumber = 42;
    printf("\nUsing typedef (uint): %u\n", positiveNumber);
    
    // Using enum
    enum Color favoriteColor = BLUE;
    printf("Favorite color (enum value): %d\n", favoriteColor);
    
    // Enum with switch
    printf("Color name: ");
    switch (favoriteColor) {
        case RED:    printf("Red\n"); break;
        case GREEN:  printf("Green\n"); break;
        case BLUE:   printf("Blue\n"); break;
        case YELLOW: printf("Yellow\n"); break;
    }
}

/*
 * Demonstrate Main Function Structure
 * -----------------------------------
 * Shows the typical organization inside main().
 */
void demonstrateMainStructure() {
    printf("\n=== 3. Main Function Structure ===\n");
    
    printf("Typical main() structure:\n\n");
    printf("int main() {\n");
    printf("    // 1. Local variable declarations\n");
    printf("    int x, y;\n");
    printf("    char name[50];\n");
    printf("\n");
    printf("    // 2. Input operations\n");
    printf("    printf(\"Enter value: \");\n");
    printf("    scanf(\"%%d\", &x);\n");
    printf("\n");
    printf("    // 3. Processing/calculations\n");
    printf("    y = x * 2;\n");
    printf("\n");
    printf("    // 4. Function calls\n");
    printf("    processData(x, y);\n");
    printf("\n");
    printf("    // 5. Output operations\n");
    printf("    printf(\"Result: %%d\", y);\n");
    printf("\n");
    printf("    // 6. Return statement\n");
    printf("    return 0;\n");
    printf("}\n");
    
    // Actual demonstration
    printf("\n--- Live Demo ---\n");
    int a = 10, b = 20;
    printf("Variable a = %d, b = %d\n", a, b);
    
    int sum = calculate(a, b, '+');
    int product = calculate(a, b, '*');
    
    printf("Sum: %d\n", sum);
    printf("Product: %d\n", product);
}

/*
 * Demonstrate User-Defined Functions
 * ----------------------------------
 * Shows different types of functions.
 */
void demonstrateFunctions() {
    printf("\n=== 4. User-Defined Functions ===\n");
    
    // Function with no return value (void)
    printf("\n4.1 Void function (no return value):\n");
    helperFunction(42);
    
    // Function with return value
    printf("\n4.2 Function with return value:\n");
    int result = calculate(15, 5, '-');
    printf("calculate(15, 5, '-') = %d\n", result);
    
    // Function with structure parameter
    printf("\n4.3 Function with structure parameter:\n");
    Person p = {"Bob", 30, 6.0};
    printPerson(p);
    
    // Demonstrating function types
    printf("\n4.4 Types of functions:\n");
    printf("  - void function(): No parameters, no return\n");
    printf("  - int function(): No parameters, returns int\n");
    printf("  - void function(int x): Takes parameter, no return\n");
    printf("  - int function(int x, int y): Parameters and return\n");
}

/*
 * Helper Function
 * ---------------
 * A simple void function that prints a value.
 */
void helperFunction(int value) {
    printf("  Helper received value: %d\n", value);
    globalCounter++;  // Modifying global variable
    printf("  Global counter is now: %d\n", globalCounter);
}

/*
 * Calculate Function
 * ------------------
 * Performs arithmetic operations and returns result.
 */
int calculate(int x, int y, char operation) {
    int result = 0;
    
    switch (operation) {
        case '+':
            result = x + y;
            break;
        case '-':
            result = x - y;
            break;
        case '*':
            result = x * y;
            break;
        case '/':
            if (y != 0) {
                result = x / y;
            } else {
                printf("Error: Division by zero!\n");
                result = 0;
            }
            break;
        default:
            printf("Error: Unknown operation '%c'\n", operation);
    }
    
    return result;
}

/*
 * Print Person Function
 * ---------------------
 * Displays information about a Person structure.
 */
void printPerson(Person p) {
    printf("  Name: %s\n", p.name);
    printf("  Age: %d years\n", p.age);
    printf("  Height: %.1f ft\n", p.height);
}

/*
 * ============================================================================
 * END OF PROGRAM
 * ============================================================================
 * 
 * Summary of Program Structure:
 * 1. Documentation (comments at top)
 * 2. Preprocessor directives (#include, #define)
 * 3. Global declarations (variables, structs, prototypes)
 * 4. main() function (entry point)
 * 5. User-defined functions (after main or with prototypes)
 * 
 * ============================================================================
 */
Examples - C Programming Tutorial | DeepML