0% found this document useful (0 votes)
3 views2 pages

C Module3 Answers

The document provides definitions and examples of arrays, specifically focusing on 2D arrays in C programming. It includes the declaration and initialization of a 2D array, along with a sample program demonstrating its usage. Additionally, it presents a binary search implementation and a program for adding two 2D matrices.

Uploaded by

asfiyak552
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

C Module3 Answers

The document provides definitions and examples of arrays, specifically focusing on 2D arrays in C programming. It includes the declaration and initialization of a 2D array, along with a sample program demonstrating its usage. Additionally, it presents a binary search implementation and a program for adding two 2D matrices.

Uploaded by

asfiyak552
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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;
}
```

You might also like