Traversing in array

Traversing in array

In traversing in array in C , each element of an array is access exactly for once for processing. This is also called visiting of an array.After insertion or deletion operation you would usually want to check whether it has been successfully  or not, to check this we can use traversing, and can make sure that whether the element is successfully insert or delete. 

Diagramatic representation

 

Traversing in array

 

 

Approach

1.Start a loop from 0 to N-1, where N is the size of array. 

2. Access every element of array with help of arr[index]

3. Print the elements. 

Algorithm

Size of List is N , a count[ counter] will have to be maintainedt o keep track of the number of elements visited.

let C is a variable for count and initialize to 1 that is lower bound of LIST.

With every visit the count C is increment and match  with upper bound N of LIST

if C is less than or equal N then the steps are repeated otherwise algorithm stops.

Algorithm step :


1. C=1
2. Process LIST[C]
3. C= C+1
4. if (C<=N) then repeat 2 and 3
5. End.

 

Program in C

#include <stdio.h>
main() {
   int arr[] = {1,3,5,7,8};
   int item = 10, k = 3, n = 5;
   int i = 0, j = n;   
   printf("The original array elements are :\n");
   for(i = 0; i<n; i++) {
      printf("arr[%d] = %d \n", i, arr[i]);
   }
}

 

Output

The original array elements are :
arr[0] = 1 
arr[1] = 3 
arr[2] = 5 
arr[3] = 7 
arr[4] = 8

Program in CPP

#include <iostream> 
using namespace std;
int main()
{ 
   int arr[5]={10, 0, 20, 0, 30};
     for (int i: arr) 
{ 
     cout<<i<<"\n"; 
}

Output

10 
20 
30 
40 
50

We can traverse the  element in array in JAVA using following method

1. Using for loop:

2. Using for each loop 

 

1.Using for loop:

In this method all where we just have to use a for loop where a counter variable accesses each element one by one.

 

Program in Java

import java.io.*; 
class ABC 
{ 
public static void main(String args[]) throws IOException 
{ 
    int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
    int i, x; 
      for (i = 0; i < ar.length; i++) 
   {
        x = ar[i];
        System.out.print(x + " "); 
    } 
}
}

Output

1 2 3 4 5 6  7 8

2. Using for each loop 

In this method for each loop optimizes the code, save typing and time.

 

Program

import java.io.*; 
class GFG 
{ 
public static void main(String args[]) throws IOException
 {
         int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
         int x; 
        for (int i : ar)
     {
       x = i; 
       System.out.print(x + " "); 
     } 
 } 
}

Output

1 2 3 4 5 6 7 8

 

Time complexity

O(n)

 

Also read the various Array operations

Insertion in array

Deletion in array 

Searching in array

Updation in array

Share this post

Leave a Reply

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