Open In App
Related Articles

C program to traverse an Array

Improve Article
Improve
Save Article
Save
Like Article
Like

Given an integer array of size N, the task is to traverse and print the elements in the array.
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  

Approach:-  

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

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

2. Access every element of array with help of 

arr[index]

3. Print the elements. 

printf("%d ", arr[i])

Below is the implementation of the above approach:  

C




// C program to traverse the array
 
#include <stdio.h>
 
// Function to traverse and print the array
void printArray(int* arr, int n)
{
    int i;
 
    printf("Array: ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
 
// Driver program
int main()
{
    int arr[] = { 2, -1, 5, 6, 0, -3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printArray(arr, n);
 
    return 0;
}

Output: 

Array: 2 -1 5 6 0 -3

 

Time Complexity: O(n)  //since one traversal of the array is required to complete all operations hence overall time required by the algorithm is linear

Auxiliary Space: O(1)// since no extra array is used so the space taken by the algorithm is constant
 

Last Updated : 13 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials