Traversing of arrays in C++(C plus plus)

Traversing is very basic and important concept of programming when we talk about arrays.This concept is same in almost every language but in this example c++ is used. There are a number of best explanations on this topic but here it is explained it in a very simple way. So, let’s get started

Definition:

By the definition  accessing/printing all the elements of an array is called Traversing of an array or a data container. 

It can be done in any data container such as Linked list, tree, stacks, Dynamic Stacks, Dynamic Queues, queues etc.
Types:

There are two main types of  traversing in c++

  1. By using while loop
  2. By using for loop

By using While loop:

This is the most simple method for traversing using while loop

int arr[5]={1,2,3,4,5}; //Declaring and initializing and integer array

//by using while loop

int k=0;

cout << “traversing by using while loop”<<endl;

while (k<5) { // Starting a while loop with the condition

cout << arr[k]<<endl; //Printing the array (You can use “cin” to take inputs as well)

k++;

}

By using For loop:

cout << “traversing by using for loop”<<endl;

int arr[5]={1,2,3,4,5};

for (int i=0;i<5;i++) { //starting a for loop

cout << arr[i]<<endl;

}

If you guys have any questions please ask in comments.

Thanks

5 Comments

Add a Comment

Your email address will not be published. Required fields are marked *