Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Array in C?
3.
Why Do We Need Arrays?
4.
Declaration of Array in C
4.1.
Example
5.
Initialization of Array in C
5.1.
Example
6.
Access Array Elements
6.1.
Example
7.
Change Value of Array Elements
7.1.
Example
8.
Input and Output Array Elements
9.
2 Dimensional Array in C
10.
Advantages of Array in C
11.
Disadvantages of Array in C
12.
Frequently Asked Questions
12.1.
What is an array in C with example?
12.2.
What is array and its types?
12.3.
What do you mean by array decay in C?
12.4.
What is the relationship between the pointer and array in C?
13.
Conclusion
Last Updated: Mar 27, 2024
Easy

Arrays in C Programming

Author Yukti Kumari
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Data structures are an integral part of computer science, enabling programmers to design efficient software. The term data structure implies a way of storing data. Many data structures are available, like arrays, stacks, queues, trees, graphs, etc.

Have you ever wondered why there are so many data structures? 

We have different data structures so that based upon the kind of data you are dealing with in your programs, you can choose an appropriate data structure that will help you perform various operations like storage, retrieval, or processing of data efficiently.

array in c programming

In this article, we will learn one of the most important Data Structures, arrays, how to declare and initialize arrays in C programming, advantages and disadvantages, and their use cases and working examples.

Let's get started.

What is Array in C?

An Array in C can be referred to as a method of combining multiple entities of similar type into a larger group. These entities or elements can be of char, int, float, or double data type or they can be of user-defined data types for eg. structures. 

In other words, an Array is a linear data structure and simply a collection of data items of the same data type, which you can access using a common name. 

You can have an array of integers, characters, floats, etc. The elements of an array are stored in contiguous memory locations.

Example - 

  • Integer Array: a[5] = {1,2,3,4,5}
     
  • Character Array: c[4] = {‘c’,’o’,’d’,’e’}, etc.

Arrays can be one-dimensional or multidimensional. A one-dimensional array can be considered a list, while a two-dimensional array looks like a table.

Let's see how to declare arrays in the next section.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why Do We Need Arrays?

Arrays are fundamental data structures that provide an established way to store and manage data in the array. Think of an array as a digital shelf with categorized compartments. Each compartment, called an index, holds data. This arrangement simplifies statistics organization and retrieval. Arrays are important because they enable efficient access to data at any index in the array, much like finding a book on a shelf with a recognized spot.

Arrays optimize memory utilization by storing data consecutively and reducing memory waste in the system. They additionally facilitate various operations, together with sorting or calculating totals, on organizations of data elements. Whether it's handling a list of names or recording temperatures through the years, arrays serve as vital gear for organizing, getting access to, and processing statistics effectively. Without arrays, managing collections of statistics would be substantially more complex and less efficient.

Declaration of Array in C

You can declare arrays just like any other variables except for the fact that you need to use square brackets[ ] after the array name for each dimension of the array. 

Rules you must follow while declaring arrays are:

  • You should always provide the dimensions of rows, columns, etc., in square brackets for uninitialized arrays.
     
  • The dimensions should always be positive integral constants or constant expressions.
     
  • If we don't initialize the array while declaring it, then the array elements contain garbage value. 

 

Memory space is allocated to the array at the time of declaration itself. 

It's important to note that an array does not change sizes later, so it is a type of static data structure.
 

The general form of declaration of arrays in C programming is:

VariableType varName[dim1, dim2, ..., dimN];

Where VariableType is a data type like integer, float, etc. and varName is the array name. 

Example

int i, j, intArray[20 ], number;
float floatArray[50];
int tableArray[2][ 5 ];      /* 2 rows and 5 columns */
const int NROWS = 100;     
const int NCOLS = 200;     
float matrix[ NROWS ][ NCOLS ]; 

Initialization of Array in C

You can initialize arrays at the time of declaration or later, just like any other variable.

We use curly braces {} to store the initialization data separated by commas after the equal sign while array declaration as shown below:

int a[5] = {1,2,3,4,5};

Let's take a look at some of the interesting points about the initialization of arrays:

  • If you initialize 1-D arrays in C programming at the time of their declaration, you may not provide its dimension. The compiler determines the size of the array from the number of elements we supply for initialization.
     
  • You can also initialize an array partially and provide fewer items than the array size. 
    The compiler initializes the remaining array elements with 0. 

Example

int intArray[ 6 ] = { 1, 2, 3, 4, 5, 6 };
float floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
double fractions[ ] = { 3.141592654, 1.570796327, 0.785398163 };  /* dimension not provided */

Access Array Elements

You can access an array element by using its index value. 

The array indices start from 0, i.e., the index of the first element of an array is 0. 

If their array size is n, then the indices range from 0 to n-1(both inclusive).

Example

int numbers[] = {25, 80, 75, 100};
printf("%d", numbers[0]);  //prints 25

Change Value of Array Elements

You can change the value of an array element by using its index and assigning it to a new value. Changing the value of array elements means modifying the data stored in specific positions within an array. 

Example

int numbers[] = {25, 80, 75, 100};
numbers[0] = 33;
printf("%d", numbers[0]);

Input and Output Array Elements

Input and output of array elements talk about how we deliver data to an array and retrieve data from the array. Think of an array like a line of box, in which each box store data.

  • Input Data into an Array: To add data into an array, we can use a loop or manually assign values to every box by index. For example, if we have an array to save the temperatures of every week, we are able to use a loop to enter every day's temperature in the array.
     
  • Output Data from an Array: Getting data from an array is like opening the box to see what is present in the box. We can use a loop to undergo each box(element) and read its content material. We will loop via and print every day's temperature for our temperature array.
     

So, inputting is like filling the boxes in the array; outputting is like checking what is within the boxes. Arrays help us prepare and work with plenty of data conveniently.

2 Dimensional Array in C

A 2-dimensional array in C is like a grid or desk. Instead of having simply one row of information, it has more than one row and column. Imagine it as a spreadsheet wherein you've got rows and columns, and each cell in the grid can store information.

For instance, in case you want to store the marks of students in a class for each subject, you may use a 2D array. Each row represents a student, and every column represents a subject. So, you may effortlessly find a student's marks in a selected subject by looking at the intersection of the row and column.

Example: 

int marks[3][4];  // This creates a 2D array with 3 rows and 4 columns

You can get access to a specific element through the use of its row and column index, like marks[1][2], to get the marks of the second student within the third subject. A 2D array in C is sort of a grid of data with rows and columns, making it suitable for organizing and accessing data in a tabular format.

Advantages of Array in C

The advantages of using arrays in C programming are as follows:

  • It helps to optimize the code by reducing the number of variables needed to store items of the same data type.
     
  • It makes it easy to access elements using their indices in O(1) time.
     
  • You can order the array elements by sorting.
     
  • Accessing elements by index has a consistent time complexity, allowing for reliable performance analysis.
     
  • Enables efficient loops for processing multiple data items.
     
  • If a user wants to store multiple values of similar type, then the Array can be used and efficiently utilized.
     
  • An array can be easily transformed into pointers.

Disadvantages of Array in C

The disadvantages of using arrays in C programming are as follows:

  • The biggest drawback of arrays is their fixed size i.e.once declared; you can't resize the array. That is why it is a static data structure.
     
  • Insertion and deletion of elements are difficult due to contiguous memory allocation.
     
  • Arrays cannot be resized dynamically.
     
  • If your data is sparse (with many empty or null values), arrays can be inefficient.
     
  • For complex data structures like trees or graphs, arrays may not be the best choice due to their simplicity.

Frequently Asked Questions

What is an array in C with example?

In C, an array is a collection of elements of the same data type stored in an adjacent memory block. For example, `int numbers[5]` creates an integer array with five boxes.

What is array and its types?

An array is like a shelf with labeled boxes for storing data. It comes in types: One-dimensional( A single row of slots), Two-dimensional (Rows and columns, like a table), and Multi-dimensional (More complex, like nested tables).

What do you mean by array decay in C?

The loss of type and dimensions of an array is known as array decay. It occurs when we pass the array into a function by pointer or value. The first address is sent to the array, which is a pointer. That is why the size of the array is not the original one.

What is the relationship between the pointer and array in C?

Arrays in C store elements of the same types, whereas Pointers are address variables that store the address of a variable. The array variable also has an address that a pointer can point to, and arrays can be navigated using a pointer.

Conclusion

In this article, we learned about arrays in C programming, how to declare and initialize arrays in C, advantages and disadvantages. We also learned their use cases and examples, along with C codes.

We hope this blog has helped you enhance your knowledge of arrays in C programming.

Check out these useful blogs on - 

Happy Reading!!‍

Previous article
Arrays
Next article
How do you Initialize an Array in C
Live masterclass