VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-traverse-an-array/

⇱ C Program to Traverse an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Traverse an Array

Last Updated : 12 Jul, 2025

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:

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


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:

  • Define a recursive function that takes the array arr and the size of the array N as arguments.
  • This function returns when all the elements are traversed.
  • It calls itself for N - 1 elements.
  • At last, prints the current element.

C Program to Traverse an Array Using Recursion


Output
Array elements using recursion: 1 2 3 4 5 

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

Comment
Article Tags: