Traversal in an array refers to the process of accessing each element in the array sequentially, typically to perform a specific operation, such as searching, sorting, or modifying the elements.
Traversing an array is essential for a wide range of tasks in programming, and the most common methods of traversal include iterating through the array using loops like for
, while
, or foreach
. Efficient traversal plays a critical role in algorithms that require scanning or manipulating data.
Examples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: "10 20 30 40 50 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [7, 8, 9, 1, 2]
Output: "7 8 9 1 2 "
Explanation: Just traverse and print the numbers.
Input: arr[] = [100, 200, 300, 400, 500]
Output: "100 200 300 400 500 "
Explanation: Just traverse and print the numbers.
Types of Array Traversal
There are mainly two types of array traversal:
1. Linear Traversal
Linear traversal is the process of visiting each element of an array sequentially, starting from the first element and moving to the last element. During this traversal, each element is processed (printed, modified, or checked) one after the other, in the order they are stored in the array. This is the most common and straightforward way of accessing the elements of an array.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Linear Traversal: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Linear Traversal: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
System.out.print("Linear Traversal: ");
for(int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Python
arr = [1, 2, 3, 4, 5]
print("Linear Traversal: ", end=" ")
for i in arr:
print(i, end=" ")
print()
C#
using System;
class Program {
static void Main() {
int[] arr = {1, 2, 3, 4, 5};
Console.Write("Linear Traversal: ");
foreach (int i in arr) {
Console.Write(i + " ");
}
Console.WriteLine();
}
}
JavaScript
const arr = [1, 2, 3, 4, 5];
console.log("Linear Traversal: ");
arr.forEach(i => {
process.stdout.write(i + ' ');
});
console.log();
OutputLinear Traversal: 1 2 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Reverse Traversal
Reverse traversal is the process of visiting each element of an array starting from the last element and moving towards the first element. This method is useful when you need to process the elements of an array in reverse order. In this type of traversal, you begin from the last index (the rightmost element) and work your way to the first index (the leftmost element).
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Reverse Traversal: ";
for(int i = n - 1; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
C
// C Code
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Reverse Traversal: ");
for(int i = n - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
// Java Code
class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
System.out.print("Reverse Traversal: ");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Python
# Python Code
arr = [1, 2, 3, 4, 5]
print("Reverse Traversal: ", end="")
for i in range(len(arr) - 1, -1, -1):
print(arr[i], end=" ")
print()
C#
// C# Code
using System;
class Program {
static void Main() {
int[] arr = {1, 2, 3, 4, 5};
int n = arr.Length;
Console.Write("Reverse Traversal: ");
for (int i = n - 1; i >= 0; i--) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
JavaScript
// JavaScript Code
let arr = [1, 2, 3, 4, 5];
console.log("Reverse Traversal: ");
for (let i = arr.length - 1; i >= 0; i--) {
process.stdout.write(arr[i] + " ");
}
console.log();
OutputReverse Traversal: 5 4 3 2 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Methods of Array Traversal
1. Using For Loop
A for
loop is a control structure that allows you to iterate over an array by specifying an initial index, a condition, and an update to the index after each iteration. It is the most common and efficient way to traverse an array because the loop can be easily controlled by setting the range of the index. This method is ideal when you know the number of elements in the array beforehand or when you need to access each element by its index.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Traversal using for loop: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Traversal using for loop: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.length;
System.out.print("Traversal using for loop: ");
for(int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Python
arr = [10, 20, 30, 40, 50]
print("Traversal using for loop: ", end=' ')
for i in arr:
print(i, end=' ')
print()
C#
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.Length;
Console.Write("Traversal using for loop: ");
for(int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
JavaScript
const arr = [10, 20, 30, 40, 50];
console.log("Traversal using for loop: ");
for(let i = 0; i < arr.length; i++) {
process.stdout.write(arr[i] + ' ');
}
console.log();
OutputTraversal using for loop: 10 20 30 40 50
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Using While Loop
A while
loop is another method to traverse an array, where the loop continues to execute as long as the specified condition is true. The key difference with the for
loop is that the loop control is more manual, and the counter or index is updated inside the loop body rather than automatically. The while
loop can be useful when the number of iterations isn't predetermined or when the loop may need to stop based on a condition other than the array size.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int i = 0;
cout << "Traversal using while loop: ";
while(i < n) {
cout << arr[i] << " ";
i++;
}
cout << endl;
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int i = 0;
printf("Traversal using while loop: ");
while(i < n) {
printf("%d ", arr[i]);
i++;
}
printf("\n");
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.length;
int i = 0;
System.out.print("Traversal using while loop: ");
while(i < n) {
System.out.print(arr[i] + " ");
i++;
}
System.out.println();
}
}
Python
arr = [10, 20, 30, 40, 50]
n = len(arr)
i = 0
print("Traversal using while loop: ", end=" ")
while i < n:
print(arr[i], end=" ")
i += 1
print()
C#
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.Length;
int i = 0;
Console.Write("Traversal using while loop: ");
while(i < n) {
Console.Write(arr[i] + " ");
i++;
}
Console.WriteLine();
}
}
JavaScript
const arr = [10, 20, 30, 40, 50];
let n = arr.length;
let i = 0;
console.log("Traversal using while loop: ");
while(i < n) {
process.stdout.write(arr[i] + ' ');
i++;
}
console.log();
OutputTraversal using while loop: 10 20 30 40 50
Time Complexity: O(n)
Auxiliary Space: O(1)
3. Using Foreach Loop (Range-based For Loop)
The foreach
loop, also known as a range-based for
loop , simplifies array traversal by directly accessing each element of the array without needing to manually manage the index. It is often used for its simplicity and readability when you just need to access or process each item in the array.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Traversal using foreach (range-based for) loop: ";
for(int value : arr) {
cout << value << " ";
}
cout << endl;
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Traversal using foreach loop: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
System.out.print("Traversal using foreach loop: ");
for(int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}
}
Python
arr = [10, 20, 30, 40, 50]
print("Traversal using foreach loop:", end=' ')
for value in arr:
print(value, end=' ')
print()
C#
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50};
Console.Write("Traversal using foreach loop: ");
foreach(int value in arr) {
Console.Write(value + " ");
}
Console.WriteLine();
}
}
JavaScript
const arr = [10, 20, 30, 40, 50];
console.log("Traversal using foreach loop:");
arr.forEach(value => {
process.stdout.write(value + ' ');
});
console.log();
OutputTraversal using foreach (range-based for) loop: 10 20 30 40 50
Time Complexity: O(n)
Auxiliary Space: O(1)
Applications of Array Traversal
Array traversal plays a key role in many operations where we need to access or modify the elements of an array. Two of the most common applications are searching elements and modifying elements.
1. Searching Elements
Traversal is often used to search for an element in an array. By visiting each element of the array sequentially, we can compare each element with the target value to determine if it exists.
Example: If you have an array of numbers, and you need to find if a specific number is present in the array, array traversal would involve checking each element one by one until a match is found or the entire array has been searched.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
int n = sizeof(arr) / sizeof(arr[0]);
bool found = false;
// Linear search using traversal
for(int i = 0; i < n; i++) {
if(arr[i] == target) {
found = true;
break;
}
}
if(found) {
cout << "Element found!" << endl;
} else {
cout << "Element not found!" << endl;
}
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int target = 30;
int n = sizeof(arr) / sizeof(arr[0]);
int found = 0;
// Linear search using traversal
for(int i = 0; i < n; i++) {
if(arr[i] == target) {
found = 1;
break;
}
}
if(found) {
printf("Element found!\n");
} else {
printf("Element not found!\n");
}
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;
// Linear search using traversal
for(int i = 0; i < arr.length; i++) {
if(arr[i] == target) {
found = true;
break;
}
}
if(found) {
System.out.println("Element found!");
} else {
System.out.println("Element not found!");
}
}
}
Python
arr = [10, 20, 30, 40, 50]
target = 30
found = False
# Linear search using traversal
for i in range(len(arr)):
if arr[i] == target:
found = True
break
if found:
print("Element found!")
else:
print("Element not found!")
C#
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
bool found = false;
// Linear search using traversal
for(int i = 0; i < arr.Length; i++) {
if(arr[i] == target) {
found = true;
break;
}
}
if(found) {
Console.WriteLine("Element found!");
} else {
Console.WriteLine("Element not found!");
}
}
}
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Modifying Elements
Array traversal is also used to modify the elements of the array. This could involve updating values, changing the order, or applying some mathematical operations to each element. For example, you can multiply every element of an array by a constant, or increase each value by 1.
Example: If you want to increase each element in an array by 5, array traversal allows you to visit each element and modify it.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
// Modifying elements using traversal (increasing each by 5)
for(int i = 0; i < n; i++) {
arr[i] += 5;
}
// Print modified array
cout << "Modified array: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
// Modifying elements using traversal (increasing each by 5)
for(int i = 0; i < n; i++) {
arr[i] += 5;
}
// Print modified array
printf("Modified array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Java
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.length;
// Modifying elements using traversal (increasing each by 5)
for(int i = 0; i < n; i++) {
arr[i] += 5;
}
// Print modified array
System.out.print("Modified array: ");
for(int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Python
arr = [10, 20, 30, 40, 50]
# Modifying elements using traversal (increasing each by 5)
for i in range(len(arr)):
arr[i] += 5
# Print modified array
print("Modified array:", end=' ')
for num in arr:
print(num, end=' ')
print()
C#
using System;
class Program {
static void Main() {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.Length;
// Modifying elements using traversal (increasing each by 5)
for(int i = 0; i < n; i++) {
arr[i] += 5;
}
// Print modified array
Console.Write("Modified array: ");
for(int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
JavaScript
let arr = [10, 20, 30, 40, 50];
// Modifying elements using traversal (increasing each by 5)
for(let i = 0; i < arr.length; i++) {
arr[i] += 5;
}
// Print modified array
console.log("Modified array:", arr.join(' '));
OutputModified array: 15 25 35 45 55
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem