Array Traversal in C: Explained with Examples and Techniques

Rumman Ansari   Software Engineer   2024-10-20 04:28:50   6270  Share
Subject Syllabus DetailsSubject Details 1 Questions
☰ TContent
☰Fullscreen

Table of Content:

Arrays are fundamental data structures in programming, widely used for storing collections of data. Array traversal is the process of accessing each element in an array sequentially. This operation is crucial for a variety of tasks, such as searching, sorting, and manipulating data. In this blog, we’ll delve into the importance of array traversal, different traversal techniques, and practical examples.


Why is Array Traversal Important?

  1. Data Access: Traversal allows access to every element in an array, making it possible to read or modify values.
  2. Searching: Many algorithms, like linear search, depend on traversing an array to find specific elements.
  3. Sorting: Array traversal is essential in sorting algorithms, enabling the comparison and rearrangement of elements.
  4. Data Manipulation: Traversing an array is necessary for tasks like calculating sums, averages, or applying transformations to the data.

Methods of Array Traversal

There are several methods to traverse an array, depending on the requirements of the task at hand. Here are the most common approaches:

1. Linear Traversal

2. Reverse Traversal

3. Using Recursion

4. Using Iterators


Array Traversal

Array Traversal
Figure: Array Traversal


Example: A list of N integer numbers is given. Write a program that travels the list and determines as to how many of the elements of the list are less than zero, zero, and greater than zero.

Solution: In this program, three counters called numNeg, numZero and numPos, would be used to keep track of the number of elements that are less than zero, zero, and greater than zero present in the list.

The required program is given below:



/* This program determines the number of less than zero, zero, and greater than zero numbers present in a list */

#include <stdio.h>

void main()

{

int List [30];

int N;

int i, numNeg, numZero, numPos;

  printf ("\n Enter the size of the list");

  scanf ("%d", &N);

printf ("Enter the elements one by one");

/* Read the List*/

for (i = 0; i < N; i++)

{

  printf ("\n Enter Number:");

  scanf ("%d", &List[i]);

}

numNeg = 0; /* Initialize counters*/

numZero = 0;

numPos = 0;

/* Travel the List*/

for (i=0; i < N; i++)

{

    if (List[i] < 0)

        numNeg = numNeg + 1;

    else

      if (List[i] == 0)

        numZero = numZero + 1;

      else

      numPos = numPos + 1;

}

}