C Program to Traverse an Array (original) (raw)

Last Updated : 26 Aug, 2024

Write a C program to traverse the given array that contains N number of elements.

**Examples

**Input: arr[] = {2, -1, 5, 6, 0, -3}
**Output: 2 -1 5 6 0 -3

**Input: arr[] = {4, 0, -2, -9, -7, 1}
**Output: 4 0 -2 -9 -7 1

Different Ways to Traverse an Array in C

Arrays are versatile data structures and C language provides the following ways to traverse the whole array:

Table of Content

**Note: It is compulsory to know the size of the array beforehand to traverse it.

1. Using a Loop

The most common and straightforward method to traverse an array is a loop. The idea is to use a loop that runs from 0 to N - 1, where N is the number of elements in the array. We can use any loop of our choice but a for loop is preferred.

C Program to Traverse an Array Using Loops

C `

// C Program to Traverse an Array using a for Loop #include <stdio.h>

int main() { int arr[] = {1, 2, 3, 4, 5}; int N = sizeof(arr) / sizeof(arr[0]);

// Traverse and print elements using a for loop
printf("Array elements using loop: ");
for (int i = 0; i < N; i++)
{
    printf("%d ", arr[i]);
}
printf("\n");

return 0;

}

`

Output

Array elements using loop: 1 2 3 4 5

**Time Complexity: O(N)
**Auxiliary Space: O(1)

2. Using Recursion

Recursion can also be used to traverse an array, although it is less efficient due to function call overhead and memory consumption. For this approach, you need to know how to pass arrays to functions in C.

**Below is the approach to use recursion to traverse the array:

C Program to Traverse an Array Using Recursion

C `

// C Program to Traverse an Array using Recursion #include <stdio.h>

// Recursive function to print array elements void traverseArray(int arr[], int N) {

// When all the elements are traversed if (N <= 0) { return; } traverseArray(arr, N - 1); printf("%d ", arr[N - 1]); }

int main() { int arr[] = {1, 2, 3, 4, 5}; int N = sizeof(arr) / sizeof(arr[0]);

// Traverse and print elements using recursion
printf("Array elements using recursion: ");
traverseArray(arr, N);
printf("\n");

return 0;

}

`

Output

Array elements using recursion: 1 2 3 4 5

**Time Complexity: O(N)
**Auxiliary Space: O(N), due to the recursive calls