Tutorial Playlist
In the realm of programming, data organisation is of utmost importance. Arrays, especially the one dimensional array in C, form the backbone of this organisation, allowing programmers to store and manage data systematically. Before delving into this one-dimensional structure, let's brush up on the basics.
In simple terms, an array is a collection of similar data types stored in contiguous memory locations. It is a fundamental data structure that enables storing and organising multiple data items of the same type. The advantage of arrays is that they allow you to access data via a single, common name, using an index or subscript that can locate each individual element.
Primarily, arrays can be categorised into two types:
1. One-dimensional arrays (1D Arrays): These are simple list-like structures that store data linearly.
2. Multi-dimensional arrays (2D, 3D, etc.): Multidimensional arrays including three or two-dimensional array in C are complex structures that store data in a matrix format.
In this article, we'll focus on the one dimensional array in C and compare it with its C++ equivalent at places.
One-dimensional arrays are the simplest form of arrays that consist of a collection of elements of the same data type arranged in sequential memory locations. Consider a one-dimensional array as a single row where you can store multiple items of the same data type.
Before an array can be used in a C program, it must be declared. The syntax for declaring an array is as follows:
datatype arrayName[arraySize]; |
Here, the datatype can be any valid C data type, the arrayName is the name of the array, and the arraySize is an integer constant greater than zero, representing the number of elements that can be stored in the array.
Once an array is declared, it can be initialised with values. Here's the syntax for array initialization:
datatype arrayName[arraySize] = {element1, element2, ..., elementN}; |
Example:
int num[5] = {1, 2, 3, 4, 5}; |
This code declares and initialises an array of integers named 'num' with five elements.
Elements in an array can be accessed using their respective index. The index of an array starts from 0 and goes up to n-1 where n is the size of the array. The syntax for accessing an array is:
arrayName[index];
Example:
int main() { |
This code will print '3', which is the third element in the array 'num'.
Declaring a one dimensional array in C involves a set of rules and regulations that must be strictly followed to ensure the correct functionality of the program. Here are some crucial rules:
The size of the array should be defined at the time of declaration. The size must be a constant integer, i.e., it cannot be a variable or a dynamic expression.
int arr[5]; // Valid |
The size of the array must be greater than zero. Negative or zero dimensions are not allowed.
int arr[5]; // Valid |
The elements of an array should all be of the same data type. You cannot have an array with mixed data types.
int arr[5]; // Valid |
If you initialise an array at the time of declaration, ensure that the number of elements does not exceed the specified size. You can, however, initialise an array with fewer elements than specified, and the remaining elements will automatically be assigned the default value of the data type (0 for integers, 0.0 for floats, '\0' for characters).
int arr[5] = {1, 2, 3, 4, 5}; // Valid |
The array name should follow the rules for identifiers in C. It can contain alphabets, digits, and underscores. However, it cannot begin with a digit.
int arr[5]; // Valid |
There are two primary methods of initialising a one dimensional array in C.
This method involves initialising an array at the time of its declaration. In this case, the size and elements of the array are defined at compile time.
Example:
int main() { |
In the above example, the array 'num' is being initialised with 5 elements during compile-time.
In run-time initialization, the array is initialised during the execution of the program, not at the compile time. This is particularly useful when inserting values into an array based on user input or some computations.
Example:
int main() { |
In this example, the program will ask the user to enter five integers, one at a time, which will be stored in the array 'num'.
To copy the contents of one array to another, we need to copy the individual elements.
Example:
int main() { |
In the above example, the elements of 'num1' are copied to 'num2' using a for loop.
While the fundamental concept of arrays remains consistent in both C and C++, there are subtle differences in functionality and features between the two languages. Let's compare these two side by side:
In C++, the syntax for declaring and initialising an array is the same as in C.
C:
int arr[5] = {1, 2, 3, 4, 5}; |
C++:
int arr[5] = {1, 2, 3, 4, 5}; |
The syntax remains the same in both languages.
In both C and C++, the sizeof operator can be used to find the size of an array. However, this only works if the array is in the scope because C and C++ don’t support reflection.
C:
int arr[5] = {1, 2, 3, 4, 5}; |
C++:
int arr[5] = {1, 2, 3, 4, 5}; |
The result will be '5' in both cases.
In C++, you have the flexibility to initialise an array without explicitly specifying the number of elements it will contain.
C:
In C, you have to provide the number of elements.
int arr[3] = {1, 2, 3}; // Valid |
C++:
In C++, you don't have to provide the number of elements.
int arr[3] = {1, 2, 3}; // Valid |
The second declaration is invalid in C but valid in C++.
C++ provides the Standard Template Library (STL), which offers a set of template classes like vector and array. These classes provide more flexible and safer array operations compared to traditional C-style arrays.
C:
In C, we don't have STL, so we have to manually manage array operations.
int arr[5] = {1, 2, 3, 4, 5}; |
C++:
In C++, using STL, we can handle arrays much more efficiently.
#include<vector> |
Arrays in C are fundamental constructs that underpin many more complex data structures and algorithms. Here are some essential points to remember about arrays in C, focusing primarily on one-dimensional arrays:
Once declared, the size of an array in C is fixed. You cannot resize it or change its length dynamically. This is why it's crucial to know the required size of the array beforehand.
An array in C can only contain elements of the same data type. It cannot store mixed data types. Consider using a structure or union if you need a data structure that can store different data types.
Array indexing in C starts from 0. That means the first element of the array is accessed with index 0, the second element with index 1, and so on. Accessing an array outside of its bounds results in undefined behavior, which could lead to program crashes or unpredictable results.
Array elements are stored in contiguous memory locations, which allows quick access to elements but can also lead to problems if not handled correctly, such as buffer overflow.
Arrays in C can be initialised at the time of declaration. However, if an array is partially initialised, elements that are not explicitly initialised receive the default value of the data type (which is 0 for numeric types).
In C, arrays are closely related to pointers. An array's name acts as a pointer to its first element. This relationship is exploited in various ways in C programming, such as passing arrays to functions, dynamic memory allocation, etc.
C does not perform any bounds checking for arrays. If you try to access or store a value in an array using an index that is outside the valid range, the compiler will not flag an error. However, this could cause serious issues, such as accessing or overwriting memory that the program does not own.
While this article primarily focuses on one-dimensional arrays, it's crucial to remember that arrays in C can be multidimensional. This feature allows you to create more complex structures, such as tables, matrices, and even tensors.
By keeping these points in mind while working with arrays in C, you can avoid common pitfalls and understand better how these crucial data structures work.
As we conclude, we understand that the one dimensional array in C is a powerful data structure. It offers simplicity while allowing us to handle large datasets. You can significantly improve your programming and problem-solving skills by understanding and mastering the concepts of arrays in C.
If you found this tutorial beneficial and are curious to dive deeper into the realm of programming, explore the Executive PG Program in Data Science offered by upGrad. This course offers valuable insights, practical experience, and industry-relevant knowledge to enhance your programming skills and excel in your programming journey.
1. How are arrays different in C++ compared to C?
The fundamental concept of arrays remains the same in C++ as in C. However, C++ includes additional features like STL (Standard Template Library), which provides ready-made templates for array manipulation.
2. Can an array include different data types?
No, an array in C can only contain elements of the same data type. However, structures and unions in C allow storing different data types.
3. What happens if we try to access an index which is out of the bounds of the array?
Accessing an array outside of its bounds results in undefined behaviour, potentially leading to a program crash or unexpected results. Hence, it's important to always ensure that we're accessing valid indices of an array.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...