Unit 5: Introduction to Arrays - Subjective Questions
CAP1008 — C Programming • Practice Questions with Detailed Answers
20 questions
Define an array. Explain how one-dimensional arrays are declared and initialized in C with suitable examples.
Array: An array is a collection of elements of the same data type stored in contiguous memory locations, referenced by a common name and accessed using an index.
Declaration syntax:
c
data_type array_name[size];
Example:
c
int marks[5];
This reserves space for 5 integers.
Initialization methods:
-
At declaration:
c
int marks[5] = {90, 85, 70, 60, 95}; -
Partial initialization (rest become 0):
c
int a[5] = {1, 2}; // a[2],a[3],a[4] = 0 -
Size inferred by compiler:
c
int a[] = {10, 20, 30}; // size = 3 -
Runtime initialization using loops:
c
for(i = 0; i < 5; i++)
scanf("%d", &marks[i]);
Key points:
- Index starts at 0 and ends at size-1.
- Elements are stored in contiguous memory.
- Accessing an out-of-bounds index leads to undefined behavior.
Explain two-dimensional arrays in C. Describe their declaration, initialization, and memory representation.
Two-dimensional array: A 2D array is a collection of elements arranged in rows and columns, essentially an array of arrays.
Declaration:
c
data_type array_name[rows][columns];
Example:
c
int matrix[3][3];
Initialization:
c
int m[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Or in a single line:
c
int m[2][3] = {1, 2, 3, 4, 5, 6};
Accessing elements:
c
m[i][j] // i = row index, j = column index
Memory representation:
- C stores 2D arrays in row-major order, meaning the entire first row is stored, then the second, and so on.
- Address of element
m[i][j]is calculated as:
Example use: Storing matrices, tables, and grids.
Write a C program to perform addition of two matrices and explain the logic.
Logic: To add two matrices, both must have the same dimensions. Each element of the resultant matrix is the sum of the corresponding elements of the two input matrices:
Program:
c
include <stdio.h>
int main() {
int a[3][3], b[3][3], c[3][3];
int i, j, r, col;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &col);
printf("Enter matrix A:\n");
for(i = 0; i < r; i++)
for(j = 0; j < col; j++)
scanf("%d", &a[i][j]);
printf("Enter matrix B:\n");
for(i = 0; i < r; i++)
for(j = 0; j < col; j++)
scanf("%d", &b[i][j]);
for(i = 0; i < r; i++)
for(j = 0; j < col; j++)
c[i][j] = a[i][j] + b[i][j];
printf("Resultant matrix:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < col; j++)
printf("%d ", c[i][j]);
printf("\n");
}
return 0;
}
Explanation: Nested loops traverse each row and column, reading inputs and computing element-wise sums into matrix c, which is then displayed.
Explain the Bubble Sort algorithm with a C program and a worked example.
Bubble Sort: A simple sorting technique where adjacent elements are repeatedly compared and swapped if they are in the wrong order. After each pass, the largest unsorted element 'bubbles up' to its correct position.
Algorithm steps:
- Compare adjacent elements.
- Swap if the left is greater than the right (for ascending order).
- Repeat for all passes until no swaps are needed.
Program:
c
include <stdio.h>
int main() {
int a[] = {5, 2, 9, 1, 3}, n = 5, i, j, temp;
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-1-i; j++) {
if(a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
Worked example on {5, 2, 9, 1, 3}:
- Pass 1:
2 5 1 3 9 - Pass 2:
2 1 3 5 9 - Pass 3:
1 2 3 5 9 - Sorted:
1 2 3 5 9
Time complexity: in worst and average cases, best case (with optimization).
Explain Linear Search and Binary Search. Distinguish between them.
Linear Search: Sequentially checks each element of the array until the target is found or the list ends.
c
for(i = 0; i < n; i++)
if(a[i] == key) { found = i; break; }
- Works on both sorted and unsorted arrays.
- Time complexity: .
Binary Search: Repeatedly divides a sorted array in half and compares the middle element with the key.
c
low = 0; high = n-1;
while(low <= high) {
mid = (low + high) / 2;
if(a[mid] == key) { found = mid; break; }
else if(a[mid] < key) low = mid + 1;
else high = mid - 1;
}
- Requires the array to be sorted.
- Time complexity: .
Differences:
| Feature | Linear Search | Binary Search |
|---|---|---|
| Data order | Any | Must be sorted |
| Complexity | ||
| Approach | Sequential | Divide and conquer |
| Speed | Slower for large data | Faster for large data |
| Simplicity | Very simple | Slightly complex |
Write a C program to implement Binary Search and trace it on an example array.
Binary Search requires a sorted array and works by dividing the search interval in half repeatedly.
Program:
c
include <stdio.h>
int main() {
int a[] = {10, 20, 30, 40, 50, 60}, n = 6;
int key = 40, low = 0, high = n-1, mid, found = -1;
while(low <= high) {
mid = (low + high) / 2;
if(a[mid] == key) { found = mid; break; }
else if(a[mid] < key) low = mid + 1;
else high = mid - 1;
}
if(found != -1)
printf("Found at index %d", found);
else
printf("Not found");
return 0;
}
Trace for key = 40 on {10,20,30,40,50,60}:
- Step 1: low=0, high=5, mid=2, a[2]=30 < 40 → low=3
- Step 2: low=3, high=5, mid=4, a[4]=50 > 40 → high=3
- Step 3: low=3, high=3, mid=3, a[3]=40 == 40 → Found at index 3
The search completed in 3 comparisons instead of 4 required by linear search.
What are character arrays and strings in C? Explain the declaration and initialization of strings.
Character array / String: In C, a string is a one-dimensional array of characters terminated by a null character '\0'. There is no separate string data type.
Declaration:
c
char str[20];
Initialization methods:
-
Character by character:
c
char name[6] = {'H','e','l','l','o','\0'}; -
String literal (null added automatically):
c
char name[6] = "Hello"; -
Size inferred:
c
char name[] = "Hello"; // size = 6 including '\0'
Key points:
-
The array size must include one extra byte for
'\0'. -
"Hello"occupies 6 bytes (5 characters + null). -
Reading input:
c
scanf("%s", name); // stops at whitespace
gets(name); // reads full line (unsafe)
fgets(name, 20, stdin); // safer -
Printing:
printf("%s", name);
The null character marks the end of the string and is essential for string functions to work correctly.
Describe the commonly used string handling functions in C with syntax and examples.
String functions are declared in the header <string.h>.
1. strlen(str) – Returns length excluding '\0':
c
int len = strlen("Hello"); // 5
2. strcpy(dest, src) – Copies src into dest:
c
strcpy(s1, "World");
3. strcat(dest, src) – Concatenates src to dest:
c
strcat(s1, s2); // s1 = s1 + s2
4. strcmp(s1, s2) – Compares two strings:
- Returns
0if equal - Negative if
s1 < s2, positive ifs1 > s2
c
if(strcmp(a, b) == 0) printf("Equal");
5. strrev(str) – Reverses the string (non-standard).
6. strlwr(str) / strupr(str) – Convert to lower/upper case (non-standard).
7. strncpy, strncat, strncmp – Bounded versions using n characters.
Example:
c
char a[20] = "Good", b[] = "Morning";
strcat(a, b); // a = "GoodMorning"
printf("%d", strlen(a)); // 11
These functions simplify string manipulation without manual character-by-character processing.
Write a C program to find the length of a string without using the strlen() function.
Logic: Traverse the character array from the beginning, incrementing a counter until the null character '\0' is reached.
Program:
c
include <stdio.h>
int main() {
char str[100];
int i = 0;
printf("Enter a string: ");
fgets(str, 100, stdin);
while(str[i] != '\0' && str[i] != '\n')
i++;
printf("Length = %d", i);
return 0;
}
Explanation:
- The loop starts at index 0.
- Each iteration checks whether the current character is the null terminator.
- The counter
iincrements until the end of the string is found. - The final value of
iequals the number of characters (excluding'\0').
Example: For input Hello, the loop runs 5 times and prints Length = 5.
Define a structure in C. Explain its declaration, definition, and initialization with an example.
Structure: A structure is a user-defined data type that groups together variables of different data types under a single name. It is used to represent a record.
Declaration:
c
struct Student {
int roll;
char name[20];
float marks;
};
Definition (creating variables):
c
struct Student s1, s2;
Initialization:
c
struct Student s1 = {101, "Ravi", 88.5};
Accessing members using the dot operator:
c
s1.roll = 101;
strcpy(s1.name, "Ravi");
s1.marks = 88.5;
printf("%d %s %.1f", s1.roll, s1.name, s1.marks);
Key points:
- Members can be of different types.
- Memory is allocated for each member separately.
structkeyword is used to define and declare.- Structures can be nested and passed to functions.
Structures are ideal for grouping related but heterogeneous data, such as student records or employee details.
What is a union in C? Explain its declaration and initialization with an example.
Union: A union is a user-defined data type similar to a structure, but all its members share the same memory location. Only one member can hold a value at any given time.
Declaration:
c
union Data {
int i;
float f;
char c;
};
Definition:
c
union Data d;
Initialization (only the first member can be initialized directly):
c
union Data d = {10};
Usage:
c
d.i = 10;
printf("%d", d.i); // valid
d.f = 3.14; // overwrites previous value
printf("%f", d.f);
Key points:
- Memory allocated = size of the largest member.
- Modifying one member affects others since they share memory.
- Useful for memory-efficient programs where only one field is used at a time.
Example: If a union has an int (4 bytes), float (4 bytes), and char (1 byte), the total size is 4 bytes, not 9.
Distinguish between a structure and a union in C.
Both structures and unions are user-defined types that group members, but they differ significantly in memory usage and behavior.
| Feature | Structure | Union |
|---|---|---|
| Keyword | struct |
union |
| Memory | Separate memory for each member | Shared memory among all members |
| Size | Sum of all member sizes (+padding) | Size of the largest member |
| Value access | All members can hold values simultaneously | Only one member at a time |
| Initialization | All members can be initialized | Only the first member |
| Use case | When all data is needed together | When only one value is used at a time |
Example:
c
struct S { int a; float b; }; // size ~8 bytes
union U { int a; float b; }; // size ~4 bytes
Summary: Structures are used when all fields must coexist, while unions save memory by reusing the same space for mutually exclusive data.
Explain how arrays are passed to functions in C with an example.
In C, arrays are always passed to functions by reference (the base address is passed), not by value. This means changes made inside the function affect the original array.
Ways to declare the parameter:
c
void display(int arr[], int n); // sized notation
void display(int *arr, int n); // pointer notation
Example:
c
include <stdio.h>
void printArray(int a[], int n) {
for(int i = 0; i < n; i++)
printf("%d ", a[i]);
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
printArray(nums, 5);
return 0;
}
Key points:
- Only the base address is passed, so the array size must be passed separately.
- The function operates directly on the original array memory.
- 2D arrays require the column size in the parameter:
c
void func(int m[][3], int rows);
This efficient mechanism avoids copying large arrays and allows functions to modify array contents.
Write a C program to find the largest and smallest elements in a one-dimensional array.
Logic: Assume the first element is both the largest and smallest, then traverse the array comparing each element and updating accordingly.
Program:
c
include <stdio.h>
int main() {
int a[100], n, i, large, small;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements: ");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
large = small = a[0];
for(i = 1; i < n; i++) {
if(a[i] > large) large = a[i];
if(a[i] < small) small = a[i];
}
printf("Largest = %d\n", large);
printf("Smallest = %d\n", small);
return 0;
}
Explanation:
largeandsmallare initialized to the first element.- The loop compares each element and updates
largeorsmall. - After the loop, both extremes are found in a single pass with time complexity .
Explain Selection Sort with an algorithm, C program, and example.
Selection Sort: Repeatedly selects the minimum element from the unsorted portion and places it at the beginning.
Algorithm:
- Find the minimum element in the unsorted part.
- Swap it with the first unsorted element.
- Move the boundary of the sorted part forward.
- Repeat until sorted.
Program:
c
include <stdio.h>
int main() {
int a[] = {29, 10, 14, 37, 13}, n = 5, i, j, min, temp;
for(i = 0; i < n-1; i++) {
min = i;
for(j = i+1; j < n; j++)
if(a[j] < a[min]) min = j;
temp = a[i]; a[i] = a[min]; a[min] = temp;
}
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
Example on {29, 10, 14, 37, 13}:
- Pass 1:
10 29 14 37 13 - Pass 2:
10 13 14 37 29 - Pass 3:
10 13 14 37 29 - Pass 4:
10 13 14 29 37 - Sorted:
10 13 14 29 37
Time complexity: in all cases.
Explain the concept of an array of structures with an example program.
Array of structures: When multiple records of the same structure type are needed, an array of structures is used. Each array element is a complete structure.
Declaration:
c
struct Student {
int roll;
char name[20];
float marks;
};
struct Student s[3];
Program:
c
include <stdio.h>
struct Student {
int roll;
char name[20];
float marks;
};
int main() {
struct Student s[3];
int i;
for(i = 0; i < 3; i++) {
printf("Enter roll, name, marks: ");
scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks);
}
printf("\nStudent Details:\n");
for(i = 0; i < 3; i++)
printf("%d %s %.2f\n", s[i].roll, s[i].name, s[i].marks);
return 0;
}
Explanation:
s[i]accesses the i-th student record.s[i].rollaccesses a member of that record.- This structure is ideal for managing lists of records such as students, employees, or products.
Write a C program to concatenate two strings without using the strcat() function.
Logic: Move to the end of the first string, then copy each character of the second string one by one, finally appending the null terminator.
Program:
c
include <stdio.h>
int main() {
char s1[100], s2[50];
int i = 0, j = 0;
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
while(s1[i] != '\0') // reach end of s1
i++;
while(s2[j] != '\0') { // copy s2 into s1
s1[i] = s2[j];
i++; j++;
}
s1[i] = '\0'; // terminate result
printf("Concatenated string: %s", s1);
return 0;
}
Explanation:
- The first loop positions the index
iat the end ofs1. - The second loop appends characters from
s2. - The null character is added to properly terminate the merged string.
- Example:
Hello+World=HelloWorld.
Explain the transpose of a matrix. Write a C program to find the transpose of a matrix.
Transpose of a matrix: The transpose is obtained by interchanging the rows and columns of a matrix. If is of order , then its transpose is of order , where:
Program:
c
include <stdio.h>
int main() {
int a[10][10], t[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("Enter matrix elements:\n");
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
scanf("%d", &a[i][j]);
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
t[j][i] = a[i][j];
printf("Transpose:\n");
for(i = 0; i < c; i++) {
for(j = 0; j < r; j++)
printf("%d ", t[i][j]);
printf("\n");
}
return 0;
}
Explanation: The element at position [i][j] in the original matrix is stored at [j][i] in the transpose. For example, a matrix becomes a matrix.
Explain nested structures in C with an example. When are they useful?
Nested structure: A structure defined inside another structure is called a nested structure. It allows grouping of related sub-records within a larger record.
Example:
c
include <stdio.h>
struct Date {
int day, month, year;
};
struct Employee {
int id;
char name[20];
struct Date doj; // nested structure
};
int main() {
struct Employee e = {101, "Amit", {15, 8, 2020}};
printf("ID: %d\n", e.id);
printf("Name: %s\n", e.name);
printf("DOJ: %d-%d-%d\n", e.doj.day, e.doj.month, e.doj.year);
return 0;
}
Accessing nested members: Use the dot operator repeatedly, e.g., e.doj.day.
Usefulness:
- Represents complex real-world entities logically (e.g., an employee with a joining date).
- Improves code organization and readability.
- Groups related data hierarchically.
Nested structures help model data that naturally contains sub-groups of information.
Describe common applications of arrays in C programming and discuss their advantages and limitations.
Applications of arrays:
- Storing lists of data: marks, salaries, temperatures.
- Sorting and searching: implementing bubble sort, selection sort, linear and binary search.
- Matrices: 2D arrays for mathematical computations, image data, and tables.
- Strings: character arrays for text processing.
- Implementing data structures: stacks, queues, and hash tables are built using arrays.
- Lookup tables: precomputed values for fast access.
Advantages:
- Random access to any element using an index in time.
- Efficient memory usage with contiguous storage.
- Easy to iterate using loops.
- Simplifies handling of large amounts of related data.
Limitations:
- Fixed size: the size must be known at compile time (for static arrays) and cannot grow dynamically.
- Homogeneous: can store only one data type.
- Insertion and deletion are costly, requiring shifting of elements ().
- No bounds checking in C leads to undefined behavior on invalid indices.
- Memory may be wasted if the array is under-utilized.
Despite limitations, arrays remain fundamental due to their simplicity and fast access.
Define an array. Explain how one-dimensional arrays are declared and initialized in C with suitable examples.
Array: An array is a collection of elements of the same data type stored in contiguous memory locations, referenced by a common name and accessed using an index.
Declaration syntax:
c
data_type array_name[size];
Example:
c
int marks[5];
This reserves space for 5 integers.
Initialization methods:
-
At declaration:
c
int marks[5] = {90, 85, 70, 60, 95}; -
Partial initialization (rest become 0):
c
int a[5] = {1, 2}; // a[2],a[3],a[4] = 0 -
Size inferred by compiler:
c
int a[] = {10, 20, 30}; // size = 3 -
Runtime initialization using loops:
c
for(i = 0; i < 5; i++)
scanf("%d", &marks[i]);
Key points:
- Index starts at 0 and ends at size-1.
- Elements are stored in contiguous memory.
- Accessing an out-of-bounds index leads to undefined behavior.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →