Module 4 - Solutions (All Questions)
1. Define 2D array. Explain declaration, initialization and passing to functions.
Definition:
A 2D array is an array of arrays. It is a grid-like structure having rows and columns.
Declaration & Initialization:
int arr[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
Accessing Elements:
printf("%d", arr[1][1]); // Output: 4
Passing to Functions:
void display(int arr[3][2]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", arr[i][j]);
printf("\n");
}
2. Multidimensional arrays with examples and applications.
Definition:
Multidimensional arrays are arrays with more than one index. A 2D array is a common example.
Example (3D Array):
int arr[2][3][4]; // 2 blocks, 3 rows, 4 columns
Application:
- Representing matrices
- Storing pixel values in images
- Managing spreadsheet-like data
- Game boards (e.g., chess, sudoku)
3. Sorting Techniques (Define and explain 3 types with examples)
Definition:
Sorting means arranging elements in a particular order (ascending or descending).
a) Bubble Sort:
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap
}
}
b) Selection Sort:
for (int i = 0; i < n-1; i++) {
int min = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min]) min = j;
// Swap arr[i] and arr[min]
c) Insertion Sort:
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
arr[j+1] = key;
4. Strings: Declaration, Initialization, and I/O Functions
Definition:
A string is a collection of characters ending with '\0' (null character).
Declaration and Initialization:
char str1[20] = "Hello";
char str2[] = {'H', 'i', '\0'};
Input/Output:
scanf("%s", str1); // Reads one word
gets(str1); // Reads full line
printf("%s", str1);
puts(str1);
Note: gets() is unsafe. Prefer fgets() in modern C.
5. Reading and Writing Strings
Reading:
char name[50];
printf("Enter name: ");
fgets(name, 50, stdin); // Reads full string with spaces
Writing:
puts(name); // Prints the string
Example:
#include <stdio.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: ");
puts(str);
return 0;