Array in C with Example

In this article, we learn how array in c programming works and how you can use declare, iterate and use array in C language.

 

Array in C

Array in C

An array in C programming is a collection of elements of the same data type that are stored in contiguous memory locations. The elements of an array are accessed using their index, which is an integer value that starts at 0.

 

Declaring an array of integers in C

int numbers[5];

 

This declares an array called “numbers” that can store 5 integers values. The elements of the array can be accessed using their index, see the below example –


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

 

In this example, the element at index 0 is assigned the value 10, the element at index 1 is assigned the value 20, and so on.

You can also initialize an array in c when you declared it see the below example –

int numbers[] = {10, 20, 30, 40, 50};

 

This declares an array called “numbers” and initializes it with the values 10, 20, 30, 40, and 50. You can use a for loop to access all the elements of an array like below –


for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

Output –

# 10 20 30 40 50

 

In C, arrays do not have a built-in size property, so every time you have to iterate the array using the loop to know the length of an array.

Now let’s understand with one more example suppose we have to check whether an element exists in an array or not.

 

Check array has an element in C

You can check if an array contains a specific element by iterating through the array and comparing each element to the element you want to check. Here’s an example of a function that checks if an array of integers contains a specific element-


#include <stdio.h>
#include <stdbool.h>

bool checkElementExist(int array[], int size, int eletoCheck) {
int i;
for (i = 0; i < size; i++) {
if (array[i] == eletoCheck) {
return true;
}
}
return false;
}

 

This function takes in three parameters, the array, its size, and the element that we want to check if it exists in the array.

 

It uses a for loop to iterate through the array and checks if the current element is equal to the element that we want to check. If it finds an element it returns true. If the loop completes without finding the target element, it returns false.

 

Now call the CheckElementExist function like below –

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

if (checkElementExist(numbers, size, 3)) {
  printf("Element found in array!");
} else {
  printf("The array does not contain the element!");

}

 

Note – if the size of the array passed to the function is not correct, the function will not work as expected.

 

Conclusion

This is how you can play with an array in c. I hope you are able to declare and iterate array elements in C programming.