C program to traverse an Array

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Array: 2 -1 5 6 0 -3

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.