Array is a collection of multiple elements. It is one of the derived data types in C programming.
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};
You can use online CSEstack IDE to execute the code shared in this tutorial.
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
We can use any looping statement in C/C++ like do
, do-while
or for
loop statement to print the 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
#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
#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.