1.
C program to find a key element in an array using Linear Search
#include <stdio.h>
int main()
{
int arr[50], n, i, key, found = 0;
// Step 1: Input array size
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Step 2: Input array elements
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// Step 3: Input key element to search
printf("Enter the key element to search: ");
scanf("%d", &key);
// Step 4: Linear search
for(i = 0; i < n; i++)
{
if(arr[i] == key)
{
printf("Element %d found at position %d.\n", key, i + 1);
found = 1;
break;
}
}
// Step 5: If element not found
if(found == 0)
printf("Element %d not found in the array.\n", key);
return 0;
}
2. Program: Sort Array Elements in Ascending Order
#include <stdio.h>
int main()
{
int arr[50], n, i, j, temp;
// Step 1: Input number of elements
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Step 2: Read array elements
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
// Step 3: Sort the array in ascending order (using simple bubble sort)
for(i = 0; i < n - 1; i++)
{
for(j = i + 1; j < n; j++)
{
if(arr[i] > arr[j])
{
// swap arr[i] and arr[j]
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// Step 4: Display sorted array
printf("\nArray elements in ascending order:\n");
for(i = 0; i < n; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
3. Sum of Two Matrices
#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int rows, cols, i, j;
// Input size of matrix
printf("Enter number of rows and columns: ");
scanf("%d %d", &rows, &cols);
// Input first matrix
printf("Enter elements of first matrix:\n");
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
scanf("%d", &a[i][j]);
// Input second matrix
printf("Enter elements of second matrix:\n");
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
scanf("%d", &b[i][j]);
// Add two matrices
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
sum[i][j] = a[i][j] + b[i][j];
// Display result
printf("Sum of two matrices:\n");
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++)
printf("%d\t", sum[i][j]);
printf("\n");
}
return 0;
}