What is Array | Print Elements in Array (Traversing)

What is Array | Print Elements in Array (Traversing)

What is an array?

Array is a collection of multiple elements. It is one of the derived data types in C programming.

Characteristics of array:

  • Elements (aka items) in the array are stored in a contiguous memory location.
  • Each element in the array has an index that is used to access that element.
  • The index of the first element in the array is 0, the index of the second element is 2, and so on.

Array in C/C++

Array in C/C++ programming can store only homogenous items i.e. items having same data types.

Syntax:

<data_type> <array_name>[<array_size>];

Array of integers

int int_arr[10];

Array of characters

char char_arr[10];

Here 10 is the size of the array. It means, it can store 10 items.

Initialing array:

Example: Initialize an integer array to store integer values from 1 to 10.

int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Array Example

You can use online CSEstack IDE to execute the code shared in this tutorial.

How to print specific element in array?

Example: Print the 3rd element in the array. The index of the 3rd element is 2 as index of the array starts with zero.

#include <stdio.h>

int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    printf("%d ", arr[2]);

    return 0;
}

Output:

3

Traversing Array

We can use any looping statement in C/C++ like do, do-while or for loop statement to print the array.

How to print array in C/C++ program using for loop? [Traversing Array]

Here is the simple code to traverse the elements in the array and print them using a for loop.

#include <stdio.h>

int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int i;

    for(i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

How to print array in C/C++ program using while loop?

#include <stdio.h>

int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int i=0;

    while(i<10) {
        printf("%d ", arr[i]);
        i++;
    }

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

How to print array in C/C++ program using do-while?

#include <stdio.h>

int main() {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int i=0;

    do {
        printf("%d ", arr[i]);
        i++;
    } while(i<10);

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

Any doubt? Write in the comment below.

Leave a Reply

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