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:
- We declare an integer array
numbers[]
containing five elements. - We determine the size of the array using
sizeof(numbers) / sizeof(numbers[0])
, which gives the number of elements. - We use a
for
loop where the variablei
starts from 0 and runs untilsize - 1
. - 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:
- We declare an integer array
numbers[]
containing five elements. - We calculate the size of the array using
sizeof(numbers) / sizeof(numbers[0])
. - We initialize an index variable
i
to 0. - The
while
loop continues as long asi
is less thansize
. - 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:
- We declare a character array
name[]
and initialize it with the string"Hello"
. - Since character arrays (strings) in C end with a null terminator
'\0'
, we can print them directly usingprintf("%s", name)
.
Output:
Hello
Conclusion
In this tutorial, we explored different methods to print an array in C:
- Using a
for
loop: The most common and efficient way to print each element of an array. - Using a
while
loop: An alternative approach where iteration depends on a condition. - Printing a character array: Strings (character arrays) can be printed directly using
printf("%s")
.