Q5 a. Define array. Explain with example.
How to declare and initialize 2D
array. [6 Marks]
Array is a collection of similar data items stored at contiguous memory locations.
**Declaration of 2D Array:**
int arr[3][3];
**Initialization:**
int arr[2][2] = {{1,2},{3,4}};
**Example Program:**
```
#include <stdio.h>
int main() {
int arr[2][2] = {{1, 2}, {3, 4}};
for(int i=0; i<2; i++) {
for(int j=0; j<2; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
```
Q5 b. Write a C program to search an element using binary search. [6 Marks]
```
#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == key) return mid;
else if(arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10}, key = 6;
int n = sizeof(arr)/sizeof(arr[0]);
int result = binarySearch(arr, n, key);
if(result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}
```
Q5 c. Write a C program to perform addition of 2D matrix. [8 Marks]
```
#include <stdio.h>
int main() {
int A[2][2] = {{1,2}, {3,4}};
int B[2][2] = {{5,6}, {7,8}};
int sum[2][2];
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
sum[i][j] = A[i][j] + B[i][j];
printf("Sum of matrices:\n");
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++)
printf("%d ", sum[i][j]);
printf("\n");
}
return 0;
}
```