top

Search

C Tutorial

.

UpGrad

C Tutorial

One Dimensional Array in C

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.

What is an Array?

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.

Types of Arrays

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.

Introduction to One Dimensional Array in C

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.

Array Declaration

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.

Array Initialization

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.

Array Accessing

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() {
   int num[5] = {1, 2, 3, 4, 5};
   printf("%d", num[2]);
   return 0;
}

This code will print '3', which is the third element in the array 'num'.

Rules for Declaring One Dimensional Array in C

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:

Fixed Size

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
int size = 5;
int arr[size]; // Invalid in C, size should be a constant

No Negative Dimension

The size of the array must be greater than zero. Negative or zero dimensions are not allowed.

int arr[5]; // Valid
int arr[0]; // Invalid
int arr[-5]; // Invalid

Data Type

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
int arr[5] = {1, "two", 3, "four", 5}; // Invalid, mixed data types

Array Initialization

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
int arr[5] = {1, 2, 3}; // Valid, the remaining elements will be set to 0
int arr[5] = {1, 2, 3, 4, 5, 6}; // Invalid, more elements than specified

Array Name

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
int 1arr[5]; // Invalid, identifier starts with digit

Initialization of One-Dimensional Array in C

There are two primary methods of initialising a one dimensional array in C.

Compile-Time Initialization

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() {
   int num[5] = {1, 2, 3, 4, 5};
   return 0;
}

In the above example, the array 'num' is being initialised with 5 elements during compile-time.

Run-Time Initialization

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() {
   int num[5];
   for(int i=0; i<5; i++) {
      printf("Enter the element for index %d: ", i);
      scanf("%d", &num[i]);
   }
   return 0;
}

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'.

Copying One-Dimensional Arrays in C

To copy the contents of one array to another, we need to copy the individual elements.

Example:

int main() {
   int num1[5] = {1, 2, 3, 4, 5};
   int num2[5];

   for(int i=0; i<5; i++) {
      num2[i] = num1[i];
   }

   // Printing elements of array num2
   for(int i=0; i<5; i++) {
      printf("%d ", num2[i]);
   }

   return 0;
}

In the above example, the elements of 'num1' are copied to 'num2' using a for loop.

Difference Between One-Dimensional Array in C++ and One Dimensional Array in C

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:

Syntax

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.

Sizeof Operator

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};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Number of elements in arr[] is: %d", size);


C++:


int arr[5] = {1, 2, 3, 4, 5};
int size = sizeof(arr)/sizeof(arr[0]);
cout << "Number of elements in arr[] is: " << size;


The result will be '5' in both cases.

Array Initialization

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
int arr[] = {1, 2, 3}; // Invalid

C++:

In C++, you don't have to provide the number of elements.

int arr[3] = {1, 2, 3}; // Valid
int arr[] = {1, 2, 3}; // Also Valid

The second declaration is invalid in C but valid in C++.

Standard Template Library (STL)

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};
// Manual operation required for traversing, sorting, etc.

C++:

In C++, using STL, we can handle arrays much more efficiently.

#include<vector>
using namespace std;

vector<int> v = {1, 2, 3, 4, 5}; //dynamic size, can be resized
// Inbuilt functions for traversing, sorting, etc.

Points to Remember About Array in C

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:

  • Fixed Size

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.

  • Homogeneous Elements

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.

  • Indexing

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.

  • Memory

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.

  • Initialization

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).

  • Arrays and Pointers

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.

  • No Bounds Checking

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.

  • Multidimensionality

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.

Conclusion

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.

FAQs

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.

Leave a Reply

Your email address will not be published. Required fields are marked *