Array in C Explained: Boost Your Coding Skills with Proven Examples
Updated on Jun 30, 2025 | 19 min read | 6.83K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Jun 30, 2025 | 19 min read | 6.83K+ views
Share:
Table of Contents
Did you know? Accessing elements in a C array is lightning-fast with an O(1) operation! This means developers can process millions of data points in the blink of an eye. In fact, benchmarks show that array operations in C can hit memory speeds of over 2,000 MB/s on modern hardware—impressive, right? |
An array is a data structure in C programming that contains a group of items of the same data type in a contiguous memory block. Each element in the array is accessible through its index, which is a numeric integer representing the element’s location within the array.
Arrays are commonly used in C programming to store and manipulate data effectively. They are capable of representing vectors, matrices, tables, and several other data structures.
In this blog, you’ll explore the concept of arrays in C, how they work, and why they are a crucial tool for efficient programming and data management.
Arrays in C are used to efficiently store and manage multiple elements of the same type in a single, contiguous block of memory. Before arrays, developers had to rely on individual variables to store related data, which was inefficient and time-consuming.
Arrays provide a systematic way to access and manipulate large sets of data, offering a simple and fast way to perform operations like searching, sorting, and updating multiple values.
By grouping similar data together and allowing indexed access, arrays make it easier to organize and process large amounts of information in a way that optimizes both time and memory usage, which is especially crucial in performance-critical applications.
In 2025, professionals who can use advanced programming techniques to streamline business operations will be in high demand. If you're looking to develop skills in in-demand programming languages, here are some top-rated courses to help you get there:
An array in C programming has the following properties:
1. Arrays can hold values of the same data type
Elements of an array can only be of the same data type. For instance, an array with an integer data type can only hold integer values, whilst an array with a character data type can only hold characters.
2. The size of an array cannot be modified
After an array has been defined, the size of the array cannot be changed at any point during the runtime. So you need to declare the array size before using it for any operations.
3. An array is index based
An array allows each element to be recognised by its unique index number, which ranges from 0 all the way up to its ‘size – 1’. You can locate specific items inside the array with the element’s index.
For example:
int arr[5] = {1, 2, 3, 4, 5};
printf(%d, arr[1]);
Will produce an output: 2
4. Contiguous memory allocation
The elements in an array are stored in contiguous memory locations. Due to this property, the items of an array can be accessed and processed more quickly.
5. The name of the array is a pointer
The name of an array is, in fact, a reference to the first element contained within the array. This indicates that you can use a pointer to send an array to a function.
6. Multi-dimensional arrays
C programming allows the creation of arrays with several dimensions called multi-dimensional arrays. For instance, a two-dimensional array is a collection of arrays in which each member is itself an array.
Also Read: 29 C Programming Projects to Try in 2025 With Source Code
Next, let’s look at how you can instantiate and initialize an array in C.
The term “instantiation” refers to the process of constructing an array in memory, allocating space for it, and giving it a variable name. Instance involves setting the array’s size and data type.
To begin using an array in your code, you must first instantiate it. After an array has been created, you can then start initialising it, i.e. storing information in it.
Let’s say you want to instantiate an array in C programming and initialise it with 5 elements. Below is the syntax to do the same:
int arr[5];
arr[5] = {1, 2, 3, 4, 5};
You can also choose to instantiate and initialise an array in the same line:
int arr[5] = {1, 2, 3, 4, 5};
‘int’ here is the data type ‘Integer’, the ‘[5]’ is the size of the array and the content within the curly braces are the elements of the array
A two-dimensional array, or 2-D array, holds information in a matrix of rows and columns. Declaring the number of rows and columns together with the data type is a prerequisite to creating and initialising a two-dimensional array. So, let’s say that we want a 2-D array of the ‘Integer’ data type of 3 rows and 4 columns we type the following syntax in C programming:
int my_array[3][4];
After we have instantiated the array, we want to store the elements 1-12 in a grid:
my_array[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8},{9, 10, 11, 12}};
The output of the array looks like:
1 2 3 4
5 6 7 8
9 10 11 12
Now that we have learnt how to instantiate and initialise an array fundamentally let’s dive a little deeper into entering elements and printing those elements.
Let’s say you want to create a program that asks a user to enter 5 elements into the array and print the elements. Here’s how you would write the code:
#include <stdio.h>
int main() {
int arr[5];
printf(“Enter 5 elements into the array:\n”);
// Loop over the array to enter the elements
for (int i = 0; i < 5; i++) {
printf(“Enter element %d: “, i + 1);
scanf(“%d”, &arr[i]);
}
printf(“The elements you entered are:\n”);
// Loop over the array to print the elements
for (int i = 0; i < 5; i++) {
printf(“%d “, arr[i]);
}
printf(“\n”);
return 0;
}
First, we create an array with the size of 5 elements, called arr. Then, using a for loop, we ask the user for the array’s first five elements. The scanf()method is then used within the loop to read the user’s inputted value and assign it to the array’s current index.
In order to print the user’s input using the printf() function, we use another for loop after all the items have been inputted. Lastly, we prepare output by printing a newline character and return 0 to signify the successful completion of the program.
Are you a full-stack developer wanting to integrate AI into your workflow? upGrad’s AI-Driven Full-Stack Development bootcamp can help you. You’ll learn how to build AI-powered software using OpenAI, GitHub Copilot, Bolt AI & more.
Also Read: Array in Java: What You Need To Know?
Next, let’s look at how you can perform linear search in an array in C.
Arrays are an essential part of C programming, providing a way to store multiple elements of the same type in a contiguous block of memory. To effectively use arrays, you need to understand and apply various operations.
Below are some key operations, with detailed explanations and usage examples.
Traversing an array means visiting each element of the array in a specific order, typically from the first to the last element. This operation is useful for displaying, processing, or performing operations on every element.
Example: In a student records system, traversing an array of student names allows you to display a list of all enrolled students.
Insertion adds a new element to a specified position in the array. To maintain the order, existing elements may need to be shifted. This operation can be done at the beginning, in the middle, or at the end of the array.
Example: In a priority queue, when a new patient with a higher priority needs to be inserted, you would add them into the sorted array of patients, pushing others down accordingly.
Deletion involves removing an element at a specific index and shifting subsequent elements left to fill the gap. This operation helps in maintaining a compact array without any empty spaces.
Example: In a contact list, if you delete a contact, the system will shift the remaining contacts up to fill the space, keeping the list continuous.
Searching in an array involves looking for a specific element by checking each index. Depending on the array's sorting order, different search algorithms like linear or binary search can be used.
Example: In an online shopping platform, when a user searches for a product, the system checks through an array of product IDs to find the matching product.
Updating an element in an array involves assigning a new value to an element at a specified index. This is a simple operation that modifies the existing data in place.
Example: In a budgeting app, you can update the cost of a specific expense item by accessing the corresponding position in the array and changing its value.
Sorting an array arranges its elements in a specific order, either ascending or descending. This is useful for efficient searching and organizing data.
Example: In a leaderboard, sorting an array of player scores allows you to rank players from highest to lowest score.
Concatenation involves joining two arrays into a single, larger array. This can be done by copying elements from both arrays into a new array.
Example: In a music playlist application, if you combine two arrays of songs, one from your favorite playlist and one from a newly added playlist, you can create one unified list.
Reversing an array involves changing the order of its elements such that the first element becomes the last, the second becomes the second last, and so on.
Example: In a photo viewer app, you may reverse an array of images so that the most recent images appear first when you go through them in reverse order.
These operations are essential for organizing and manipulating data efficiently, and they're widely used in many real-world applications, from data processing to user interfaces.
Also Read: PHP Array Push Explained: Add, Modify, and Optimize Arrays
Next, let’s look at how you can perform linear searching using an array in C.
A linear search, also known as a sequential search, involves going through a list or array’s elements one by one, starting at the beginning and continuing until the sought-after item is located or the end of the list is reached.
In simpler words, a linear search algorithm works by iteratively comparing each element of the array or list to the target element, beginning with the first member and continuing until the target element is located or the end of the array or list is reached.
Below is a simple program using a linear search on an array to find out the target element:
#include <stdio.h>
int main() {
int arr[] = {5, 7, 12, 8, 3};
int n = sizeof(arr)/ sizeof(arr[0]); // using the sizeof function to find out the length of the array
int target = 8; // this is the element we want to find
int flag = 0; // flag to indicate whether target element is found, originally set to false
for (int i = 0; i < n; i++) { // using a for loop to iterate through the array
if (arr[i] == target) {
flag = 1;
printf(“Element found at index %d\n”, i);
break; // exiting the loop once target element is found
}
}
if (!flag) {
printf(“Element not found\n”);
}
return 0;
}
Explanation: This code performs a linear search to find a target element (8) in the array arr[]. It calculates the array's length using sizeof(arr) / sizeof(arr[0]), then iterates through the array. If the target is found, it sets the flag to 1 and prints the index, exiting the loop early. If not, it prints "Element not found".
Output:
Element found at index 3
In this case, the element 8 is found at index 3 in the array.
Also Read: Arrays in Python: What are Arrays in Python & How to Use Them?
Next, let’s look at how you can perform bubble sort an array in C.
Bubble sort is a straightforward technique for sorting an array in ascending or descending order. It constantly compares nearby array items and exchanges them if their order is incorrect. The procedure is continued until the array is in the desired order.
Sample Code:
The syntax for implementing a bubble sort in C programming is given below:
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]); // returns the length of the array
int i, j, temp;
for (i = 0; i < n-1; i++) { // outer loop
for (j = 0; j < n-i-1; j++) { // inner loop
if (arr[j] > arr[j+1]) { // checking if element at current index is greater than the element at the next index
// performing standard swapping using a temporary variable
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf(“Sorted array: “);
for (i = 0; i < n; i++) {
printf(“%d “, arr[i]);
}
printf(“\n”);
return 0;
}
Explanation: This code implements the Bubble Sort algorithm to sort an array of integers. It uses two nested loops: the outer loop controls the number of passes through the array, while the inner loop compares adjacent elements and swaps them if they are in the wrong order.
After each pass, the largest unsorted element is placed in its correct position. The process continues until the array is fully sorted. The sorted array is then printed in ascending order.
Output:
Sorted array: 11 12 22 25 34 64 90
Also Read: Multidimensional Array in PHP [With Examples]
Next, let’s look at some of the best practices to follow when working with an array in C.
Following best practices is essential to ensure that your code is efficient, maintainable, and error-free. Poor handling of arrays can lead to issues like memory leaks, buffer overflows, or inefficient performance. By adhering to best practices, you can avoid common pitfalls, make your code more robust, and enhance its readability and maintainability.
Let’s explore some key best practices that will help you work effectively with arrays in C.
It’s crucial to define the size of the array explicitly to avoid errors like accessing uninitialized memory or running into buffer overflows.
Example:
#define SIZE 10
int arr[SIZE]; // Array of size 10
In this example, using a #define ensures that the array size is consistent throughout the program and can be easily adjusted in one place.
Output: The size of the array arr is defined as 10. If you try to access arr[10], it would result in an out-of-bounds error since the array only has indices from 0 to 9.
Using constants or macros to define the size of arrays allows you to change the size later without having to modify the array’s declaration throughout the code. It also makes your code more adaptable and reusable.
Example:
const int MAX_SIZE = 100;
int arr[MAX_SIZE]; // Array of size defined by a constant
This approach makes it easy to update the array size across your program without having to manually change each occurrence.
Output: This code defines an array arr with a size of 100. You could change MAX_SIZE at the top of the program to easily adjust the size of the array without modifying each usage of arr.
Buffer overflow occurs when you access elements outside the bounds of an array. This can lead to unpredictable behavior, crashes, or security vulnerabilities. Always ensure that array indices are within the valid range.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int index = 4; // Valid index
if (index >= 0 && index < sizeof(arr)/sizeof(arr[0])) {
printf("%d", arr[index]); // Safe array access
}
Here, checking the index before accessing ensures that we don't access elements outside the bounds of the array, preventing potential crashes.
Output:
5
The program safely accesses arr[4], which is the last element of the array, and prints its value, which is 5. The check ensures that the index is within bounds, avoiding out-of-bounds errors.
When working with dynamic arrays (using malloc, calloc, etc.), it's important to manage memory correctly to prevent memory leaks or inefficient memory usage. Always free dynamically allocated memory when done.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int index = 4; // Valid index
if (index >= 0 && index < sizeof(arr)/sizeof(arr[0])) {
printf("%d", arr[index]); // Safe array access
}
By freeing dynamically allocated memory with free(), you avoid memory leaks, which can accumulate over time and lead to performance degradation or system crashes.
Output: This code allocates memory for an array of 10 integers, and then frees the memory using free(). While there’s no direct output, this ensures proper memory management and avoids memory leaks.
Uninitialized arrays may contain garbage values, leading to unpredictable behavior. Always initialize arrays before use to ensure they hold known values.
Example:
int arr[5] = {0}; // Initializing all elements to 0
This ensures that all elements in the array are initialized to 0, preventing issues that may arise from reading uninitialized memory.
By following these best practices, you can significantly reduce the likelihood of bugs, improve the efficiency of your program, and make your code more maintainable.
Also Read: String Array In Java: Java String Array With Coding Examples
Next, let’s look at how upGrad can help you learn the usage of array in C.
Arrays are useful for implementing a wide variety of data structures, including stacks, queues, and hash tables, and allow for quick access to specific items by index. They are a cornerstone of many data structures, as mentioned above; therefore, they naturally come up in interviews for software engineering roles.
This is where upGrad comes in. Its comprehensive programs provide structured learning, mock interviews, and mentorship from industry experts, helping thousands successfully land high-paying roles at top tech companies.
In addition to the courses covered in the blog, here are some additional programs that can help you in your learning journey:
If you're unsure where to begin or which area to focus on, upGrad’s expert career counselors can guide you based on your goals. You can also visit a nearby upGrad offline center to explore course options, get hands-on experience, and speak directly with mentors!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Reference:
https://softwareengineering.stackexchange.com/questions/302354/memory-cache-performance-in-working-with-arrays-in-c
900 articles published
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources