Print an Array in C

In C, we can print an array by iterating through its elements using loops like for, while, or do-while. The most common way to print an array is by using a for loop, which allows us to access each element and display it using the printf() function. This tutorial will cover different methods to print an array with examples.


Examples of Printing an Array

1. Print an Integer Array Using a for Loop

In this example, we will use a for loop to iterate through an integer array and print its elements.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    // Using for loop to print array elements
    for (int i = 0; i < size; i++) {
        printf("%d ", numbers[i]);
    }

    return 0;
}

Explanation:

  1. We declare an integer array numbers[] containing five elements.
  2. We determine the size of the array using sizeof(numbers) / sizeof(numbers[0]), which gives the number of elements.
  3. We use a for loop where the variable i starts from 0 and runs until size - 1.
  4. Inside the loop, we use printf() to print each element of the array.

Output:

1 2 3 4 5

2. Print an Array Using a while Loop

In this example, we will use a while loop to traverse an integer array and print each element.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int i = 0;

    // Using while loop to print array elements
    while (i < size) {
        printf("%d ", numbers[i]);
        i++;
    }

    return 0;
}

Explanation:

  1. We declare an integer array numbers[] containing five elements.
  2. We calculate the size of the array using sizeof(numbers) / sizeof(numbers[0]).
  3. We initialize an index variable i to 0.
  4. The while loop continues as long as i is less than size.
  5. Inside the loop, we print the current element and increment i.

Output:

10 20 30 40 50

3. Print a Character Array (String)

In this example, we will print a character array (string) using printf() directly.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char name[] = "Hello";

    // Printing string directly
    printf("%s", name);

    return 0;
}

Explanation:

  1. We declare a character array name[] and initialize it with the string "Hello".
  2. Since character arrays (strings) in C end with a null terminator '\0', we can print them directly using printf("%s", name).

Output:

Hello

Conclusion

In this tutorial, we explored different methods to print an array in C:

  1. Using a for loop: The most common and efficient way to print each element of an array.
  2. Using a while loop: An alternative approach where iteration depends on a condition.
  3. Printing a character array: Strings (character arrays) can be printed directly using printf("%s").