CoreTechED

Loading

Learn to print alternate array elements using iterative, recursive, and pointer approaches. Master array traversal with practical C examples.

Alternate Elements of an Array: Complete Guide

Alternate Elements of an Array: A Comprehensive Tutorial

Printing alternate elements of an array is a fundamental array traversal problem that demonstrates basic loop control and indexing. The task is to print every other element starting from the first element (index 0).

This tutorial provides an in-depth exploration of printing alternate array elements: the iterative approach, recursive approach, practical implementations in C, edge cases, common pitfalls, and best practices.


Conceptual Introduction & Fundamentals

What are Alternate Elements?

Alternate elements are elements at even indices (0, 2, 4, …) when starting from the first element. We skip every other element.

Example:

text

Array: [10, 20, 30, 40, 50] Alternate elements: 10, 30, 50 (indices 0, 2, 4)

Why This Problem Matters

  • Basic loop control: Understanding index manipulation.
  • Array traversal patterns: Foundation for more complex algorithms.
  • Interview preparation: Common beginner-level question.
  • Pattern recognition: Identify elements at regular intervals.

Approaches

ApproachTime ComplexitySpace Complexity
IterativeO(n)O(1)
RecursiveO(n)O(n) for stack

Syntax & Core Mechanics

Iterative Approach

Start from index 0, print element, increment by 2.

c

#include <stdio.h> /* Prints alternate elements (even indices) */ void getAlternates(int arr[], int n) { for (int i = 0; i < n; i += 2) { printf("%d ", arr[i]); } printf("\n"); } int main(void) { int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Alternate elements: "); getAlternates(arr, n); return 0; }

Expected output:

text

Alternate elements: 10 30 50

Time Complexity: O(n/2) = O(n)
Auxiliary Space: O(1)

Recursive Approach

c

#include <stdio.h> /* Recursive function to print alternate elements */ void getAlternatesRecursive(int arr[], int n, int index) { if (index >= n) { return; // Base case: end of array } printf("%d ", arr[index]); /* Recursive call with index + 2 */ getAlternatesRecursive(arr, n, index + 2); } int main(void) { int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Alternate elements (recursive): "); getAlternatesRecursive(arr, n, 0); printf("\n"); return 0; }

Expected output:

text

Alternate elements (recursive): 10 30 50

Time Complexity: O(n)
Auxiliary Space: O(n) for recursive call stack

Alternative: Using Pointer Arithmetic

c

#include <stdio.h> /* Using pointer arithmetic */ void printAlternatesPointer(int arr[], int n) { for (int *p = arr; p < arr + n; p += 2) { printf("%d ", *p); } printf("\n"); } int main(void) { int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Alternate elements (pointer): "); printAlternatesPointer(arr, n); return 0; }

Expected output:

text

Alternate elements (pointer): 10 30 50

Full Practical Code Example with Explanation

This program demonstrates multiple approaches to printing alternate elements with edge cases and performance comparison.

Program: Alternate Elements Printer

c

/** * alternate_elements.c * Demonstrates printing alternate elements using iterative, * recursive, and pointer approaches. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <errno.h> #define MAX_LINE_LEN 100 /* Function prototypes */ void printAlternatesIterative(const int arr[], int n); void printAlternatesRecursive(const int arr[], int n, int index); void printAlternatesPointer(const int arr[], int n); void demonstrateIterative(void); void demonstrateRecursive(void); void demonstratePointer(void); void demonstrateEdgeCases(void); void demonstratePerformance(void); void printArray(const int arr[], int n); int readInteger(const char *prompt, int *outValue); int main(void) { int choice; char buffer[MAX_LINE_LEN]; printf("=== Alternate Elements Printer ===\n"); while (1) { printf("\n--- Menu ---\n"); printf("1. Iterative Approach\n"); printf("2. Recursive Approach\n"); printf("3. Pointer Approach\n"); printf("4. Edge Cases\n"); printf("5. Performance Comparison\n"); printf("6. Exit\n"); printf("Enter choice: "); fflush(stdout); if (fgets(buffer, sizeof(buffer), stdin) == NULL) { fprintf(stderr, "Error reading choice.\n"); return EXIT_FAILURE; } choice = atoi(buffer); switch (choice) { case 1: demonstrateIterative(); break; case 2: demonstrateRecursive(); break; case 3: demonstratePointer(); break; case 4: demonstrateEdgeCases(); break; case 5: demonstratePerformance(); break; case 6: printf("Exiting.\n"); return EXIT_SUCCESS; default: printf("Invalid choice. Please try again.\n"); break; } } return EXIT_SUCCESS; } /* Iterative approach: O(n) time, O(1) space */ void printAlternatesIterative(const int arr[], int n) { for (int i = 0; i < n; i += 2) { printf("%d ", arr[i]); } printf("\n"); } /* Recursive approach: O(n) time, O(n) space */ void printAlternatesRecursive(const int arr[], int n, int index) { if (index >= n) { return; } printf("%d ", arr[index]); printAlternatesRecursive(arr, n, index + 2); } /* Pointer approach: O(n) time, O(1) space */ void printAlternatesPointer(const int arr[], int n) { for (const int *p = arr; p < arr + n; p += 2) { printf("%d ", *p); } printf("\n"); } /* Demonstrates iterative approach */ void demonstrateIterative(void) { printf("\n=== Iterative Approach ===\n"); int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Array: "); printArray(arr, n); printf("Alternate elements: "); printAlternatesIterative(arr, n); printf("Time: O(n), Space: O(1)\n"); } /* Demonstrates recursive approach */ void demonstrateRecursive(void) { printf("\n=== Recursive Approach ===\n"); int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Array: "); printArray(arr, n); printf("Alternate elements: "); printAlternatesRecursive(arr, n, 0); printf("\n"); printf("Time: O(n), Space: O(n) for stack\n"); } /* Demonstrates pointer approach */ void demonstratePointer(void) { printf("\n=== Pointer Approach ===\n"); int arr[] = {10, 20, 30, 40, 50}; int n = sizeof(arr) / sizeof(arr[0]); printf("Array: "); printArray(arr, n); printf("Alternate elements: "); printAlternatesPointer(arr, n); printf("Time: O(n), Space: O(1)\n"); } /* Demonstrates edge cases */ void demonstrateEdgeCases(void) { printf("\n=== Edge Cases ===\n"); /* Case 1: Empty array */ int emptyArr[] = {}; int emptyN = 0; printf("Empty array: "); printAlternatesIterative(emptyArr, emptyN); printf("(no elements)\n"); /* Case 2: Single element */ int singleArr[] = {42}; int singleN = sizeof(singleArr) / sizeof(singleArr[0]); printf("Single element: "); printAlternatesIterative(singleArr, singleN); /* Case 3: Two elements */ int twoArr[] = {1, 2}; int twoN = sizeof(twoArr) / sizeof(twoArr[0]); printf("Two elements: "); printAlternatesIterative(twoArr, twoN); /* Case 4: Even number of elements */ int evenArr[] = {1, 2, 3, 4, 5, 6}; int evenN = sizeof(evenArr) / sizeof(evenArr[0]); printf("Even elements: "); printAlternatesIterative(evenArr, evenN); /* Case 5: Odd number of elements */ int oddArr[] = {1, 2, 3, 4, 5}; int oddN = sizeof(oddArr) / sizeof(oddArr[0]); printf("Odd elements: "); printAlternatesIterative(oddArr, oddN); /* Case 6: Negative elements */ int negArr[] = {-5, 1, 4, 2, 12}; int negN = sizeof(negArr) / sizeof(negArr[0]); printf("Negative elements: "); printAlternatesIterative(negArr, negN); } /* Demonstrates performance */ void demonstratePerformance(void) { printf("\n=== Performance Comparison ===\n"); int n = 1000000; int *arr = malloc(n * sizeof(int)); if (arr == NULL) { perror("malloc failed"); return; } for (int i = 0; i < n; i++) { arr[i] = i; } /* Iterative */ clock_t start = clock(); volatile int sum = 0; for (int i = 0; i < n; i += 2) { sum += arr[i]; } clock_t end = clock(); double iterativeTime = ((double)(end - start)) / CLOCKS_PER_SEC * 1000; /* Pointer */ start = clock(); sum = 0; for (const int *p = arr; p < arr + n; p += 2) { sum += *p; } end = clock(); double pointerTime = ((double)(end - start)) / CLOCKS_PER_SEC * 1000; printf("Array size: %d\n", n); printf("Iterative approach: %.3f ms\n", iterativeTime); printf("Pointer approach: %.3f ms\n", pointerTime); free(arr); } /* Prints array */ void printArray(const int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); }

Explanation of Approaches

  1. Iterative: Loop with i += 2 starting from 0.
  2. Recursive: Function calls itself with index + 2.
  3. Pointer: Pointer arithmetic with p += 2.
  4. Edge cases: Handles empty, single, even, odd, negative arrays.

Expected Output (partial)

text

=== Alternate Elements Printer === --- Menu --- 1. Iterative Approach 2. Recursive Approach 3. Pointer Approach 4. Edge Cases 5. Performance Comparison 6. Exit Enter choice: 1 === Iterative Approach === Array: 10 20 30 40 50 Alternate elements: 10 30 50 Time: O(n), Space: O(1) --- Menu --- ... Enter choice: 4 === Edge Cases === Empty array: (no elements) Single element: 42 Two elements: 1 Even elements: 1 3 5 Odd elements: 1 3 5 Negative elements: -5 4 12 --- Menu --- ... Enter choice: 5 === Performance Comparison === Array size: 1000000 Iterative approach: 0.456 ms Pointer approach: 0.431 ms

Common Pitfalls, Edge Cases & Memory Considerations

1. Off-by-One in Loop

Using i <= n instead of i < n causes out-of-bounds access.

c

for (int i = 0; i <= n; i += 2) { // BUG printf("%d ", arr[i]); }

Solution: Use i < n.

2. Empty Array

Accessing arr[0] on empty array is undefined.

Solution: Check n > 0 or use loop condition.

3. Negative Array Elements

Alternate printing works with negative numbers.

Solution: No special handling needed for negatives.

4. Recursive Stack Overflow

Deep recursion for large arrays.

Solution: Use iterative approach for large arrays.

5. Not Using const

Function should use const for read-only access.

c

void printAlternates(const int arr[], int n);

6. Pointer Arithmetic Out of Bounds

Pointer going beyond array end.

Solution: Use p < arr + n as loop condition.

7. Integer Overflow in Index

Very large indices overflow int.

Solution: Use size_t for indices.

8. Memory Leaks

Forgetting to free dynamically allocated arrays.

Solution: Always free allocated memory.

9. Not Handling n=0

Division by zero or empty array issues.

Solution: Check for empty array.

10. Memory Considerations

  • Iterative: O(1) extra space.
  • Recursive: O(n) stack space.
  • Pointer: O(1) extra space.
  • No additional memory needed beyond input array.

Summary & Best Practices

Printing alternate elements is a simple yet fundamental array problem that demonstrates loop control and indexing. The iterative approach is preferred for its O(1) space efficiency.

Key Takeaways

  • Alternate elements: even indices (0, 2, 4, …).
  • Iterative: O(n) time, O(1) space.
  • Recursive: O(n) time, O(n) space.
  • Pointer arithmetic: O(n) time, O(1) space.
  • Handle edge cases: empty, single, even/odd length.

Best Practices

  1. Use iterative approach for O(1) space.
  2. Use const for read-only array parameters.
  3. Check for empty arrays.
  4. Use size_t for indices.
  5. Handle both even and odd lengths.
  6. Test with edge cases.
  7. Document complexity in comments.
  8. Use pointer arithmetic for performance-critical code.
  9. Free allocated memory.
  10. Profile performance for large arrays.

By mastering this simple problem, you’ll build foundation skills for more complex array manipulation tasks.