Practice questions on Arrays
Last Updated :
28 Dec, 2024
In this article, we will discuss some important concepts related to arrays and problems based on that. Before understanding this, you should have basic idea about Arrays.
Type 1. Based on array declaration -
These are few key points on array declaration:
- A single dimensional array can be declared as int a[10] or int a[] = {1, 2, 3, 4}. It means specifying the number of elements is optional in 1-D array.
- A two dimensional array can be declared as int a[2][4] or int a[][4] = {1, 2, 3, 4, 5, 6, 7, 8}. It means specifying the number of rows is optional but columns are mandatory.
- The declaration of int a[4] will give the values as garbage if printed. However, int a[4] = {1,1} will initialize remaining two elements as 0.
Que - 1.
Predict output of following program
int main()
{
int i;
int arr[5] = {1};
for (i = 0; i < 5; i++)
printf("%d ", arr[i]);
return 0;
}
(A) 1 followed by four garbage values: (B) 1 0 0 0 0 (C) 1 1 1 1 1 (D) 0 0 0 0 0
Solution:
As discussed, if array is initialized with few elements, remaining elements will be initialized to 0. Therefore, 1 followed by 0, 0, 0, 0 will be printed.
Que - 2.
Predict output of the following program:
int main()
{
int a[][] = {{1,2},{3,4}};
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
printf("%d ", a[i][j]);
return 0;
}
(A) 1 2 3 4 (B) Compiler Error in line ” int a[][] = {{1,2},{3,4}};” (C) 4 garbage values (D) 4 3 2 1
Solution:
As discussed, specifying the number of columns in 2-D array is mandatory, so, it will give compile time error.
Type 2. Finding address of an element with given base address -
When an array is declared, a contiguous block of memory is assigned to it which helps in finding address of elements from base address. For a single dimensional array a[100], address of ith element can be found as:
addr(a[i]) = BA+ i*SIZE
Where BA represents base address (address of 0th element) and SIZE represents size of each element in the array. For a two dimensional array x[3][3], the elements can be represented as:

As 2-D array is stored in row major order in C language, row 0 will be stored first followed by row 1 and row 2. For finding the address of x[2][2], we need to go to 2nd row (each row having 3 elements). After reaching 2nd row, it can be accessed as single dimensional array. Therefore, we need to go to 2nd element of the array. Assuming BA as 0 and size as 1, the address of x[2][2] will be 0 + (2 * 3 + 2) * 1 = 8. For a given array with m rows and n columns, the address can be calculated as:
add(a[i][j]) = BA + (i*n + j) * SIZE
Where BA represents base address (address of 0th element), n represents number of columns in 2-D array and SIZE represents size of each element in the array.
Que - 3.
Consider the following declaration of a ‘two-dimensional array in C:
char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of a[40][50] is: (GATE CS 2002) (A) 4040 (B) 4050 (C) 5040 (C) 5050
Solution:
Using the formula discussed,
addr[40][50] = 0 + (40*100 + 50) * 1 = 4050
Que - 4.
For a C program accessing X[i][j][k], the following intermediate code is generated by a compiler. Assume that the size of an integer is 32 bits and the size of a character is 8 bits. (GATE-CS-2014)
t0 = i * 1024
t1= j * 32
t2 = k * 4
t3 =t1 + t0
t4 = t3 + t2
t5 = X[t4]
Which one of the following statement about the source code of C program is correct? (A) X is declared as “int X[32][32][8]” (B) X is declared as “int X[4][1024][32]” (C) X is declared as “char X[4][32][8]” (D) X is declared as “char X[32][16][2]”
Solution:
For a three dimensional array X[10][20][30], we have 10 two dimensional matrices of size [20]*[30]. Therefore, for a 3 D array X[M][N][O], the address of X[i][j][k] can be calculated as:
BA + (i*N*O+j*O+k)*SIZE
Given different expressions, the final value of t5 can be calculated as:
t5 = X[t4] = X[t3+t2] = X[t1+t0+t2] = X[i*1024+j*32+k*4]
By equating addresses,
(i*N*O+j*O+k)SIZE = i*1024+j*32+k*4 = (i*256+j*8+k)4
Comparing the values of i, j and SIZE, we get
SIZE = 4, N*O = 256 and O = 8, hence, N = 32
As size is 4, array will be integer. The option which matches value of N and O and array as integer is (A).
Type 3. Accessing array elements using pointers -
- In a single dimensional array a[100], the element a[i] can be accessed as a[i] or *(a+i) or *(i+a)
- Address of a[i] can be accessed as &a[i] or (a+i) or (i+a)
- In two dimensional array a[100][100], the element a[i][j] can be accessed as a[i][j] or *(*(a+i)+j) or *(a[i]+j)
- Address of a[i][j] can be accessed as &a[i][j] or a[i]+j or *(a+i)+j
- In two dimensional array, address of ith row can be accessed as a[i] or *(a+i)
Que - 5.
Assume the following C variable declaration
int *A [10], B[10][10];
Of the following expressions
I. A[2]
II. A[2][3]
III. B[1]
IV. B[2][3]
which will not give compile-time errors if used as left hand sides of assignment statements in a C program (GATE CS 2003)? (A) I, II, and IV only (B) II, III, and IV only (C) II and IV only (D) IV only
Solution:
As given in the question, A is an array of 10 pointers and B is a two dimensional array. Considering this, we take an example as:
int *A[10], B[10][10];
int C[] ={1, 2, 3, 4, 5};
As A[2] represents an integer pointer, it can store the address of integer array as: A[2] = C; therefore, I is valid. As A[2] represents base address of C, A[2][3] can be modified as: A[2][3] = *(C +3) = 0; it will change the value of C[3] to 0. Hence, II is also valid. As B is 2D array, B[2][3] can be modified as: B[2][3] = 5; it will change the value of B[2][3] to 5. Hence, IV is also valid. As B is 2D array, B[2] represent address of 2nd row which can’t be used at LHS of statement as it is invalid to modify the address. Hence III is invalid.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem