Arrays In C++
Topic asked in February 2022 (CBCS) , July 2022 (CBCS) , September 2021 (CBCS) , March 2021 (CBCS) and June 2018 (CBCS) question paper.
An array in C++ is a collection of elements of the same data type stored in contiguous memory locations. It provides a way to store multiple values of the same data type under a single name. Each element in the array is accessed by its index, which represents its position within the array.
Need for Arrays in C++
Arrays are essential in C++ programming for several reasons:
- Storage Efficiency: Arrays allow efficient storage of multiple values of the same data type in contiguous memory locations. This enables optimized memory usage compared to individual variables.
- Access and Manipulation: Arrays provide a convenient way to access and manipulate a group of related elements using a single identifier and index notation. This simplifies code readability and organization.
- Iteration and Processing: Arrays facilitate iteration over a sequence of elements using loops such as for or while. This makes it easier to perform repetitive operations on collections of data.
- Data Organization: Arrays are useful for organizing and managing data in structured formats, such as lists, matrices, tables, or databases. They allow for easy representation and manipulation of multidimensional data structures.
- Passing to Functions: Arrays can be passed as arguments to functions, enabling modular and reusable code. Functions can operate on array elements without needing to know the exact size or contents of the array.
- Efficient Memory Access: Accessing elements of an array by index allows for efficient random access, as the memory locations are contiguous. This results in faster read and write operations compared to non-contiguous data structures.
One Dimensional Array in C++
A one-dimensional array in C++ is a collection of elements of the same data type arranged sequentially in memory. It allows for efficient storage and manipulation of a fixed-size sequence of elements.
Declaration/Initialization of One-Dimensional Array
Declaration of One-Dimensional Array
To declare a one-dimensional array in C++, you use the following syntax:
Where:
- dataType specifies the type of data that the array will hold (e.g., int, float, char, etc.).
- arrayName is the identifier or name given to the array.
- arraySize represents the number of elements that the array can store.
For example, if you want to declare an array named numbers of size 5 to hold integers, you would write:
This statement declares an array named numbers that can store 5 integer values.
Initialization of One-Dimensional Array
After declaring an array, you can initialize its elements at the time of declaration using braces . There are several ways to initialize the array:
Initializing with Values:
You can provide a list of initial values enclosed in braces at the time of declaration. The number of values provided must match the size of the array. For example:
This initializes the numbers array with values 1, 2, 3, 4, and 5 at indices 0 to 4 respectively.
Partial Initialization:
You can partially initialize the array, leaving some elements uninitialized. In this case, the remaining elements are automatically initialized to zero. For example:
This initializes the numbers array with values 1 and 2 at indices 0 and 1 respectively, and sets the remaining elements at indices 2 to 4 to 0.
Initializing without Specifying Size:
If you don't specify the size of the array, the compiler can infer it from the number of initial values provided. For example:
Inputting Array Elements
You can input elements into an array using a loop or individually assign values to each element of the array.
Example (Input without using Loop):
- An array named numbers of size 5 is declared.
- The program prompts the user to enter 5 numbers.
- The cin statements individually input values into each element of the numbers array.
- The user input is stored in the respective elements of the array.
Example (Input using Loop):
- This program prompts the user to input 5 numbers.
- Each number input by the user is stored in the respective element of the numbers array.
Accessing and Printing Array Elements
Array elements can be accessed using their index within square brackets []. Array indexing starts from 0 for the first element and goes up to arraySize - 1.
Example (Accessing Array Elements):
Output:
Explanation:
- The program declares and initializes an array numbers with the values
{10, 20, 30, 40, 50}
. - It then prints each element of the array along with its index using a loop.
- The loop iterates from 0 to 4 (inclusive), accessing each element of the array using its index.
- The output displays each array element along with its corresponding index.
Passing One-dimensional Array to a Function
Output:
Here,
- The array arr is declared and initialized with five integer values:
{1, 2, 3, 4, 5}.
- The printArray() function is called with two arguments: the array arr and the size of the array, which is 5.
- Inside the printArray() function, a for loop iterates through each element of the array arr.
- During each iteration of the loop, the value of the current element of the array is printed followed by a space.
- After printing all the elements of the array, the loop terminates, and the function execution completes.
Program to Find Sum of Array Elements
Output:
Explanation:
This program first defines an array arr
with some integer values. It then calculates the size of the array using the formula sizeof(arr) / sizeof(arr[0])
,
where sizeof(arr)
gives the total size of the array in bytes, and sizeof(arr[0])
gives the size of one element in the array.
Dividing the total size by the size of one element gives the number of elements in the array.
Next, it iterates through the array using a for loop and adds each element to the sum variable. Finally, it prints the sum of the array elements to the console.
Two-Dimensional Array in C++
A two-dimensional array in C++ is a collection of elements arranged in rows and columns. It can be visualized as a grid or matrix where each element is identified by its row and column index.
Declaration/Initialization of a Two-Dimensional Array
In C++, you can declare and initialize a two-dimensional array using the following syntax:
Where:
- dataType specifies the type of data stored in the array (e.g., int, float, char, etc.).
- arrayName is the identifier used to access the array.
- rows and cols represent the number of rows and columns in the array, respectively.
{element11, element12, ..., element1cols}
to{elementrows1, elementrows2, ..., elementrowscols}
are initial values for each element of the array.
Example:
In this example, a two-dimensional array named matrix of size 3x3 is declared and initialized with the values.
Inputting Array Elements
You can input elements into a two-dimensional array using nested loops or individually assign values to each element of the array.
Example (Input without using Nested Loop):
- This program prompts the user to input elements for a 3x3 matrix.
- Each element input by the user is directly stored in the respective position of the matrix array without using a nested loop.
- The program explicitly prompts the user to enter each element separately and then reads the input using cin.
Example (Input using Nested Loop):
- This program prompts the user to input elements for a 3x3 matrix.
- Each element input by the user is stored in the respective position of the matrix array.
Accessing Array Elements
Array elements in a two-dimensional array can be accessed using two indices representing row and column.
Example (Accessing Array Elements):
Output:
- The program declares and initializes a 3x3 array named matrix with the assigned values.
- The outer loop iterates over each row of the array (i represents the row index).
- The inner loop iterates over each column of the array within the current row (j represents the column index).
- Inside the inner loop, each element of the array is accessed using its row and column indices (matrix[i][j]) and printed to the console.
- After printing all the elements in a row, a newline character (endl) is used to move to the next line for the next row.
- This process repeats for each row and column, printing all elements of the array in a 3x3 grid format.
Passing Two-dimensional Array to a Function
Output:
Explanation:
- The 2D array arr is declared and initialized with two rows and three columns.
- The printArray() function is called with three arguments: the 2D array arr, the number of rows (2), and the number of columns (3).
- Inside the printArray() function, a nested loop iterates through each element of the 2D array.
- During each iteration of the nested loop, the value of the current element of the array is printed followed by a space.
- After printing all the elements of the array, the inner loop terminates, and a newline is printed to move to the next row.
- This process continues until all elements of the 2D array are printed.
Differences Between 1D and 2D Arrays
Aspect | 1D Array | 2D Array |
---|---|---|
Dimension | Single-dimensional | Two-dimensional |
Declaration | Declared using a single set of square brackets [ ] | Declared using two sets of square brackets [ ][ ] |
Access | Accessed using a single index | Accessed using two indices (row and column) |
Memory Allocation | Contiguous block of memory | Contiguous blocks of memory arranged in rows and columns |
Usage | Suitable for linear data representation | Suitable for representing tabular data, matrices, etc. |
Advantages And Disadvantage of Arrays
Advantages
- Efficient Data Storage: Arrays provide an efficient way to store a collection of elements of the same data type in contiguous memory locations.
- Random Access: Elements in an array can be accessed randomly by their index, allowing for quick retrieval or modification of elements at any position within the array.
- Simple Syntax: Arrays have a simple and straightforward syntax for declaration and usage, making them easy to understand and implement in code.
- Compact Code: Using arrays can lead to more compact and concise code, especially when dealing with repetitive tasks or operations on multiple elements.
- Iterative Operations: Arrays are well-suited for iterative operations such as traversing, searching, and sorting, making them versatile for various algorithms and data manipulation tasks.
Disadvantages
- Fixed Size: Arrays have a fixed size, set at the time of declaration, which cannot be changed dynamically. This can lead to inefficiencies in memory usage.
- Static Memory Allocation: Arrays allocate memory statically, leading to potential memory wastage or insufficiency if the array size is not optimized.
- Sequential Storage: Elements in an array are stored sequentially in memory, which can result in slower performance for certain operations like insertion or deletion of elements.
- Homogeneous Data Types: Arrays can only store elements of the same data type, limiting their flexibility for storing heterogeneous data or complex structures.
- No Built-in Bounds Checking: Most programming languages do not provide built-in bounds checking for array accesses, which can lead to runtime errors or undefined behavior if accessing elements outside the array bounds.
Last updated on -