Unit4 - Subjective Questions
CSE101 • Practice Questions with Detailed Answers
Define an array in C. Explain the syntax for declaring and initializing a One-Dimensional (1D) array with examples.
Definition: An array is a collection of variables of the same data type that are referenced by a common name. The specific element in an array is accessed by an index.
1. Declaration Syntax:
To declare an array, you specify the type of the elements, the name of the array, and the number of elements (size).
Example:
int marks[5]; declares an integer array of size 5.
2. Initialization:
Arrays can be initialized at the time of declaration.
- Complete Initialization:
int numbers[5] = {10, 20, 30, 40, 50}; - Partial Initialization:
int numbers[5] = {10, 20};(Remaining elements become 0). - Initialization without Size:
int numbers[] = {1, 2, 3};(Compiler determines size as 3).
Explain how elements of a 1D array are stored in memory. If the base address of an integer array is 1000 and the size of an integer is 2 bytes, calculate the address of .
Memory Storage:
Elements of a 1D array are stored in contiguous memory locations. The index starts from 0.
Address Calculation Formula:
The address of the element is calculated as:
Calculation:
- Base Address () = 1000
- Size of integer () = 2 bytes
- Index () = 5
Therefore, the element is stored at address 1010.
Write a C program to find the sum and average of elements stored in an array.
Here is the C program to find the sum and average:
c
include <stdio.h>
int main() {
int n, i;
float sum = 0, average;
int arr[100];
printf("Enter the number of elements: ");
scanf("%d", &n);
// Input array elements
for(i = 0; i < n; ++i) {
printf("Enter number %d: ", i + 1);
scanf("%d", &arr[i]);
sum += arr[i]; // Add to sum
}
average = sum / n;
printf("Sum = %.2f
", sum);
printf("Average = %.2f
", average);
return 0;
}
Logic:
- Read the number of elements .
- Use a loop to accept input and simultaneously add the value to the
sumvariable. - Divide
sumbynto get theaverage.
Differentiate between One-Dimensional and Two-Dimensional arrays. Provide the syntax for declaring a 2D array.
Differences:
| Feature | One-Dimensional (1D) Array | Two-Dimensional (2D) Array |
|---|---|---|
| Structure | Linear list of elements. | Table of elements (Rows and Columns). |
| Subscript | Uses one subscript (e.g., a[i]). |
Uses two subscripts (e.g., a[i][j]). |
| Memory | Stored contiguously. | Stored as a sequence of 1D arrays (Row-major in C). |
| Use Case | Storing lists, vectors. | Storing matrices, tables. |
2D Array Syntax:
Example: int matrix[3][3]; declares a matrix with 3 rows and 3 columns.
Explain Row-Major and Column-Major ordering for storing 2D arrays. Derive the address calculation formula for Row-Major order.
1. Row-Major Order:
In this method, elements are stored row by row. The entire first row is stored, followed by the second row, and so on. C uses Row-Major ordering.
2. Column-Major Order:
Elements are stored column by column. The entire first column is stored, followed by the second column, etc.
Address Calculation (Row-Major):
Given an array (where is rows, is columns), Base Address , and element size .
To find the address of element at row and column ():
We must skip full rows to reach the starting of the row. Each row has elements.
Total elements skipped = .
Formula:
Write a C program to perform Matrix Addition for two matrices.
c
include <stdio.h>
int main() {
int a[3][3], b[3][3], sum[3][3];
int i, j;
// Input Matrix A
printf("Enter elements of 1st matrix:
");
for (i = 0; i < 3; ++i)
for (j = 0; j < 3; ++j)
scanf("%d", &a[i][j]);
// Input Matrix B
printf("Enter elements of 2nd matrix:
");
for (i = 0; i < 3; ++i)
for (j = 0; j < 3; ++j)
scanf("%d", &b[i][j]);
// Adding Matrices
for (i = 0; i < 3; ++i)
for (j = 0; j < 3; ++j)
sum[i][j] = a[i][j] + b[i][j];
// Displaying Result
printf("Sum of two matrices:
");
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
printf("%d ", sum[i][j]);
}
printf("
");
}
return 0;
}
Describe the mechanism of passing arrays to functions in C. How does passing a 1D array differ from passing a single variable?
Passing Mechanism:
When an array is passed to a function, the base address (address of the first element) of the array is passed, not a copy of the entire array. This is effectively Call by Reference.
Syntax:
- Function Prototype:
void myFunction(int arr[], int size); - Function Call:
myFunction(myArray, 5);(Note: brackets[]are not used in the call).
Difference from Single Variable:
- Single Variable: Usually passed by value (a copy is created). Changes inside the function do not affect the original variable.
- Array: Passed by address. Any modification made to the array elements inside the function will modify the original array in the calling function.
Write a C program to multiply two matrices. Include checks for compatibility of matrix dimensions.
Logic: Two matrices and can be multiplied only if . The resulting matrix will be .
c
include <stdio.h>
int main() {
int a[10][10], b[10][10], mul[10][10];
int m, n, p, q, i, j, k;
printf("Enter rows and columns for first matrix: ");
scanf("%d %d", &m, &n);
printf("Enter rows and columns for second matrix: ");
scanf("%d %d", &p, &q);
if (n != p) {
printf("Error! Matrices cannot be multiplied.");
} else {
// Input A
printf("Enter elements of matrix A:
");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
// Input B
printf("Enter elements of matrix B:
");
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
scanf("%d", &b[i][j]);
// Initialization of result matrix
for (i = 0; i < m; i++)
for (j = 0; j < q; j++)
mul[i][j] = 0;
// Multiplication Logic
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
for (k = 0; k < n; k++) {
mul[i][j] += a[i][k] * b[k][j];
}
}
}
// Output
printf("Resultant Matrix:
");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++)
printf("%d\t", mul[i][j]);
printf("
");
}
}
return 0;
}
Explain the algorithm to insert an element into a specific position in a 1D array.
Algorithm for Insertion:
Assuming an array arr with n elements and capacity to hold more.
- Input: Read the element to be inserted (
key) and the position (pos) where it needs to be inserted. - Validation: Check if the array is full. If yes, print "Overflow".
- Shift Elements:
- Start a loop from the last index (
n-1) down to the target index (pos-1). - Move the element at current index
itoi+1.
- Start a loop from the last index (
- Insert: Place the
keyat the specified position. - Update Size: Increment the number of elements by 1.
Write a function in C to delete an element from an array given its position.
c
void deleteElement(int arr[], int n, int pos) {
// pos is the user-friendly position (1-based)
// n is the pointer to the current size of array
if (pos < 1 || pos > *n) {
printf("Invalid position!
");
return;
}
// Shifting elements to the left to overwrite the deleted element
// Loop starts from index pos-1 (the element to delete)
for (int i = pos - 1; i < *n - 1; i++) {
arr[i] = arr[i + 1];
}
// Decrement the size of the array
(*n)--;
printf("Element deleted successfully.
");
}
Explanation:
- The function takes the array, a pointer to the size (so the change persists), and the position.
- It shifts all elements from
posto the end one step to the left (). - Finally, it reduces the count of elements.
What is Linear Search? Write a C program to implement Linear Search.
Definition:
Linear Search (or Sequential Search) is the simplest searching algorithm. It traverses the array sequentially from the first element to the last element, checking if the current element matches the search key.
C Program:
c
include <stdio.h>
int main() {
int array[100], search, c, n;
printf("Enter number of elements in array
");
scanf("%d", &n);
printf("Enter %d integer(s)
", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search
");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) {
printf("%d is present at location %d.
", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.
", search);
return 0;
}
Explain the logic of Binary Search. What is the mandatory prerequisite for Binary Search? Calculate its Time Complexity.
Logic:
Binary Search is a divide-and-conquer algorithm.
- Compare the search key with the middle element of the array.
- If the key matches the middle element, the search is successful.
- If the key is smaller than the middle element, repeat the search in the left half.
- If the key is larger, repeat the search in the right half.
- Repeat until the key is found or the interval is empty.
Prerequisite:
The array must be sorted (in ascending or descending order).
Time Complexity:
In every step, the search space is divided by 2.
- Best Case: (Element found at middle).
- Worst Case: .
Write a C program to implement Binary Search algorithm recursively or iteratively.
Iterative Binary Search Implementation:
c
include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (arr[m] == x)
return m;
// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return -1; // Not found
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1)
printf("Element not found");
else
printf("Element found at index %d", result);
return 0;
}
Compare Linear Search and Binary Search based on efficiency and requirements.
| Criteria | Linear Search | Binary Search |
|---|---|---|
| Prerequisite | None (Array can be unsorted). | Array must be sorted. |
| Approach | Sequential access. | Divide and Conquer. |
| Time Complexity | (Proportional to size). | (Logarithmic). |
| Efficiency | Slower for large datasets. | Very fast for large datasets. |
| Implementation | Simple. | Slightly complex (Index calculations). |
| Dataset Access | Can work on Random or Sequential access (like Linked List). | Requires Random Access (Direct indexing needed). |
What is Bubble Sort? Explain its working principle with an example pass.
Definition:
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Working Principle:
- Compare and . If , swap them.
- Compare and . Swap if necessary.
- Continue this until the end of the array. After the first pass, the largest element "bubbles up" to the last position.
- Repeat the process for the remaining elements (, , etc.).
Example Pass (Array: 5, 1, 4, 2, 8):
- ( 5 1 4 2 8 ) ( 1 5 4 2 8 ) // Swap 5, 1
- ( 1 5 4 2 8 ) ( 1 4 5 2 8 ) // Swap 5, 4
- ( 1 4 5 2 8 ) ( 1 4 2 5 8 ) // Swap 5, 2
- ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) // No Swap
- Largest element 8 is now at the end.
Write a C program to sort an array of integers in ascending order using Bubble Sort.
c
include <stdio.h>
int main() {
int array[100], n, c, d, swap;
printf("Enter number of elements
");
scanf("%d", &n);
printf("Enter %d integers
", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
// Bubble Sort Logic
for (c = 0; c < n - 1; c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1]) { /* For descending order use < */
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:
");
for (c = 0; c < n; c++)
printf("%d
", array[c]);
return 0;
}
Trace the Bubble Sort algorithm for the input array: {64, 34, 25, 12, 22}. Show the array status after every pass.
Input: {64, 34, 25, 12, 22}
Pass 1:
- Compare 64, 34 -> Swap ->
{34, 64, 25, 12, 22} - Compare 64, 25 -> Swap ->
{34, 25, 64, 12, 22} - Compare 64, 12 -> Swap ->
{34, 25, 12, 64, 22} - Compare 64, 22 -> Swap ->
{34, 25, 12, 22, 64} - Result: 64 is sorted at the end.
Pass 2:
- Compare 34, 25 -> Swap ->
{25, 34, 12, 22, 64} - Compare 34, 12 -> Swap ->
{25, 12, 34, 22, 64} - Compare 34, 22 -> Swap ->
{25, 12, 22, 34, 64} - Result: 34 is sorted.
Pass 3:
- Compare 25, 12 -> Swap ->
{12, 25, 22, 34, 64} - Compare 25, 22 -> Swap ->
{12, 22, 25, 34, 64} - Result: 25 is sorted.
Pass 4:
- Compare 12, 22 -> No Swap ->
{12, 22, 25, 34, 64} - Result: Array is fully sorted.
Write a C program to find the Transpose of a given Matrix.
The transpose of a matrix is obtained by swapping rows with columns. Element at [i][j] moves to [j][i].
c
include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("Enter matrix elements:
");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j)
scanf("%d", &a[i][j]);
// Computing transpose
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
printf("Transpose of the matrix:
");
for (i = 0; i < c; ++i) { // Note: Loop runs c times then r times
for (j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
}
printf("
");
}
return 0;
}
What are the advantages and limitations of using Arrays in C?
Advantages:
- Random Access: Any element can be accessed instantly using the index ( complexity).
- Code Optimization: Less code required to store multiple variables of the same type.
- Traversal: Easy to traverse using loops.
- Sorting/Searching: Algorithms like Binary search work efficiently on arrays.
Limitations:
- Fixed Size: The size of the array must be known at compile time (static arrays). It cannot be resized dynamically at runtime.
- Contiguous Memory: Requires a single block of contiguous memory, which might cause allocation failures if memory is fragmented.
- Insertion/Deletion: Expensive operations because they require shifting existing elements to maintain order.
Write a C program to find the largest and smallest element in an array along with their indices.
c
include <stdio.h>
int main() {
int arr[50], n, i, max, min, maxPos, minPos;
printf("Enter number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Initialize with first element
max = arr[0]; min = arr[0];
maxPos = 0; minPos = 0;
for (i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
maxPos = i;
}
if (arr[i] < min) {
min = arr[i];
minPos = i;
}
}
printf("Largest element is %d at index %d
", max, maxPos);
printf("Smallest element is %d at index %d
", min, minPos);
return 0;
}