c

examples

examples.c🔧
/**
 * @file examples.c
 * @brief Loop Examples (for, while, do-while)
 * 
 * This file demonstrates all loop types in C.
 * 
 * Compile: gcc -Wall examples.c -o examples
 * Run: ./examples
 */

#include <stdio.h>

/* ============================================================
 * EXAMPLE 1: BASIC FOR LOOP
 * ============================================================ */
void example_basic_for() {
    printf("\n=== Example 1: Basic for Loop ===\n");
    
    // Count from 1 to 5
    printf("Count 1-5: ");
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    printf("\n");
    
    // Count down from 5 to 1
    printf("Countdown: ");
    for (int i = 5; i >= 1; i--) {
        printf("%d ", i);
    }
    printf("\n");
    
    // Count by 2s
    printf("By 2s (0-10): ");
    for (int i = 0; i <= 10; i += 2) {
        printf("%d ", i);
    }
    printf("\n");
}

/* ============================================================
 * EXAMPLE 2: BASIC WHILE LOOP
 * ============================================================ */
void example_basic_while() {
    printf("\n=== Example 2: Basic while Loop ===\n");
    
    // Count 1 to 5 with while
    printf("Count 1-5: ");
    int i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    printf("\n");
    
    // Halve until less than 1
    printf("Halving 100: ");
    double value = 100.0;
    while (value >= 1.0) {
        printf("%.1f ", value);
        value /= 2;
    }
    printf("\n");
}

/* ============================================================
 * EXAMPLE 3: BASIC DO-WHILE LOOP
 * ============================================================ */
void example_basic_do_while() {
    printf("\n=== Example 3: Basic do-while Loop ===\n");
    
    // Count 1 to 5 with do-while
    printf("Count 1-5: ");
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    printf("\n");
    
    // Shows do-while executes at least once
    printf("Execute once (condition false): ");
    int x = 10;
    do {
        printf("%d ", x);
    } while (x < 5);  // Condition is false, but body ran once
    printf("\n");
}

/* ============================================================
 * EXAMPLE 4: ARRAY TRAVERSAL
 * ============================================================ */
void example_array_traversal() {
    printf("\n=== Example 4: Array Traversal ===\n");
    
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    // Forward traversal
    printf("Forward: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // Backward traversal
    printf("Backward: ");
    for (int i = size - 1; i >= 0; i--) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // Calculate sum
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    printf("Sum: %d\n", sum);
}

/* ============================================================
 * EXAMPLE 5: STRING PROCESSING
 * ============================================================ */
void example_string_loop() {
    printf("\n=== Example 5: String Processing ===\n");
    
    char str[] = "Hello, World!";
    
    // Print each character
    printf("Characters: ");
    for (int i = 0; str[i] != '\0'; i++) {
        printf("[%c] ", str[i]);
    }
    printf("\n");
    
    // Count characters (manual strlen)
    int len = 0;
    while (str[len] != '\0') {
        len++;
    }
    printf("Length: %d\n", len);
    
    // Count specific character
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == 'l') {
            count++;
        }
    }
    printf("Count of 'l': %d\n", count);
}

/* ============================================================
 * EXAMPLE 6: MULTIPLE LOOP VARIABLES
 * ============================================================ */
void example_multiple_variables() {
    printf("\n=== Example 6: Multiple Loop Variables ===\n");
    
    // Two counters
    printf("Two counters (i up, j down):\n");
    for (int i = 0, j = 5; i <= 5; i++, j--) {
        printf("  i=%d, j=%d\n", i, j);
    }
    
    // Finding middle
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    int size = 7;
    printf("\nFinding elements from both ends:\n");
    for (int left = 0, right = size - 1; left <= right; left++, right--) {
        if (left == right) {
            printf("  Middle: %d\n", arr[left]);
        } else {
            printf("  Pair: %d and %d\n", arr[left], arr[right]);
        }
    }
}

/* ============================================================
 * EXAMPLE 7: ACCUMULATOR PATTERNS
 * ============================================================ */
void example_accumulators() {
    printf("\n=== Example 7: Accumulator Patterns ===\n");
    
    // Sum of 1 to 100
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    printf("Sum of 1-100: %d\n", sum);
    
    // Product (factorial)
    int n = 5;
    long factorial = 1;
    for (int i = 2; i <= n; i++) {
        factorial *= i;
    }
    printf("%d! = %ld\n", n, factorial);
    
    // Finding maximum
    int arr[] = {34, 78, 12, 89, 45, 67};
    int size = 6;
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    printf("Maximum: %d\n", max);
    
    // Counting
    int count = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] > 50) {
            count++;
        }
    }
    printf("Numbers > 50: %d\n", count);
}

/* ============================================================
 * EXAMPLE 8: POWER AND FIBONACCI
 * ============================================================ */
void example_math_sequences() {
    printf("\n=== Example 8: Mathematical Sequences ===\n");
    
    // Power calculation: 2^10
    int base = 2, exp = 10;
    long power = 1;
    for (int i = 0; i < exp; i++) {
        power *= base;
    }
    printf("%d^%d = %ld\n", base, exp, power);
    
    // Fibonacci sequence
    int n = 10;
    printf("First %d Fibonacci: ", n);
    int a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        printf("%d ", a);
        int next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
}

/* ============================================================
 * EXAMPLE 9: INPUT VALIDATION LOOP
 * ============================================================ */
void example_input_validation() {
    printf("\n=== Example 9: Input Validation ===\n");
    
    // Simulating input validation (using predefined values)
    int testInputs[] = {-5, 150, 25};
    int inputIndex = 0;
    int age;
    
    printf("Validating age inputs:\n");
    do {
        age = testInputs[inputIndex++];
        printf("  Input: %d - ", age);
        
        if (age < 0 || age > 120) {
            printf("Invalid (must be 0-120)\n");
        } else {
            printf("Valid!\n");
            break;
        }
    } while (inputIndex < 3);
}

/* ============================================================
 * EXAMPLE 10: MENU SYSTEM
 * ============================================================ */
void example_menu_system() {
    printf("\n=== Example 10: Menu System ===\n");
    
    int choices[] = {1, 2, 3, 5, 4};  // Simulate user choices
    int choiceIndex = 0;
    int choice;
    
    do {
        printf("\n--- MENU ---\n");
        printf("1. View Balance\n");
        printf("2. Deposit\n");
        printf("3. Withdraw\n");
        printf("4. Exit\n");
        
        choice = choices[choiceIndex++];
        printf("Choice: %d\n", choice);
        
        switch (choice) {
            case 1:
                printf("Balance: $1000.00\n");
                break;
            case 2:
                printf("Depositing...\n");
                break;
            case 3:
                printf("Withdrawing...\n");
                break;
            case 4:
                printf("Goodbye!\n");
                break;
            default:
                printf("Invalid choice!\n");
        }
    } while (choice != 4 && choiceIndex < 5);
}

/* ============================================================
 * EXAMPLE 11: PATTERN PRINTING
 * ============================================================ */
void example_patterns() {
    printf("\n=== Example 11: Pattern Printing ===\n");
    
    int n = 5;
    
    // Right triangle
    printf("Right triangle:\n");
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    
    // Inverted triangle
    printf("\nInverted triangle:\n");
    for (int i = n; i >= 1; i--) {
        for (int j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n");
    }
    
    // Number pyramid
    printf("\nNumber pyramid:\n");
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            printf("%d ", j);
        }
        printf("\n");
    }
}

/* ============================================================
 * EXAMPLE 12: INFINITE LOOP WITH EXIT
 * ============================================================ */
void example_infinite_loop() {
    printf("\n=== Example 12: Controlled Infinite Loop ===\n");
    
    int commands[] = {'r', 's', 'p', 'q'};  // Simulated commands
    int cmdIndex = 0;
    
    printf("Simulated command processor:\n");
    
    while (1) {  // Infinite loop
        char cmd = commands[cmdIndex++];
        printf("Command: %c -> ", cmd);
        
        if (cmd == 'q') {
            printf("Quit\n");
            break;  // Exit infinite loop
        }
        
        switch (cmd) {
            case 'r': printf("Running\n"); break;
            case 's': printf("Stopping\n"); break;
            case 'p': printf("Pausing\n"); break;
            default: printf("Unknown\n");
        }
        
        if (cmdIndex >= 4) break;  // Safety exit
    }
}

/* ============================================================
 * EXAMPLE 13: PRIME NUMBERS
 * ============================================================ */
void example_prime_numbers() {
    printf("\n=== Example 13: Prime Numbers ===\n");
    
    int limit = 50;
    printf("Prime numbers up to %d:\n", limit);
    
    for (int num = 2; num <= limit; num++) {
        int isPrime = 1;
        
        // Check if num is divisible by any number up to sqrt(num)
        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = 0;
                break;
            }
        }
        
        if (isPrime) {
            printf("%d ", num);
        }
    }
    printf("\n");
}

/* ============================================================
 * EXAMPLE 14: DIGIT PROCESSING
 * ============================================================ */
void example_digit_processing() {
    printf("\n=== Example 14: Digit Processing ===\n");
    
    int number = 12345;
    int original = number;
    
    // Count digits
    int count = 0;
    int temp = number;
    while (temp > 0) {
        count++;
        temp /= 10;
    }
    printf("Number: %d has %d digits\n", original, count);
    
    // Sum of digits
    int sum = 0;
    temp = number;
    while (temp > 0) {
        sum += temp % 10;
        temp /= 10;
    }
    printf("Sum of digits: %d\n", sum);
    
    // Reverse number
    int reversed = 0;
    temp = number;
    while (temp > 0) {
        reversed = reversed * 10 + temp % 10;
        temp /= 10;
    }
    printf("Reversed: %d\n", reversed);
}

/* ============================================================
 * MAIN FUNCTION
 * ============================================================ */
int main() {
    printf("╔════════════════════════════════════════════════╗\n");
    printf("║    LOOPS - EXAMPLES (for, while, do-while)     ║\n");
    printf("║    Iteration in C                              ║\n");
    printf("╚════════════════════════════════════════════════╝\n");
    
    example_basic_for();
    example_basic_while();
    example_basic_do_while();
    example_array_traversal();
    example_string_loop();
    example_multiple_variables();
    example_accumulators();
    example_math_sequences();
    example_input_validation();
    example_menu_system();
    example_patterns();
    example_infinite_loop();
    example_prime_numbers();
    example_digit_processing();
    
    printf("\n=== All Examples Completed! ===\n");
    
    return 0;
}
Examples - C Programming Tutorial | DeepML