1.
C Program for Swapping Two Variables
----------------------------------------
Algorithm:
1. Start
2. Input two variables
3. Use a temp variable to swap
4. Display values
5. Stop
Code:
#include <stdio.h>
int main() {
int a = 10, b = 20, temp;
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d", a, b);
return 0;
}
Output:
After swapping: a = 20, b = 10
2. C Program for Selection Sort
-------------------------------
Algorithm:
1. Start
2. Loop through array
3. Find minimum in each pass
4. Swap with current index
5. Print array
Code:
#include <stdio.h>
int main() {
int a[5] = {64, 25, 12, 22, 11};
int i, j, min, temp;
for (i = 0; i < 4; i++) {
min = i;
for (j = i + 1; j < 5; j++) {
if (a[j] < a[min])
min = j;
}
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
printf("Sorted array: ");
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}
Output:
Sorted array: 11 12 22 25 64
3. C Program for Linear Search
------------------------------
Algorithm:
1. Start
2. Input array and key
3. Traverse and compare
4. If match, print index
5. Else, not found
Code:
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50}, key = 30, i;
for (i = 0; i < 5; i++) {
if (a[i] == key) {
printf("Element found at index %d", i);
return 0;
}
}
printf("Element not found");
return 0;
}
Output:
Element found at index 2
4. C Program for Binary Search
------------------------------
Algorithm:
1. Start
2. Set low=0, high=n-1
3. Find mid, compare with key
4. Adjust low/high
5. Repeat until found or low > high
Code:
#include <stdio.h>
int main() {
int a[] = {10, 20, 30, 40, 50};
int low = 0, high = 4, mid, key = 30;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
printf("Element found at index %d", mid);
return 0;
} else if (a[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
printf("Element not found");
return 0;
}
Output:
Element found at index 2
5. Addition of Two Matrices
----------------------------
Algorithm:
1. Input two matrices
2. Add each element
3. Store in third matrix
4. Display result
Code:
#include <stdio.h>
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2], i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];
printf("Result:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++)
printf("%d ", c[i][j]);
printf("\n");
}
return 0;
}
Output:
Result:
68
10 12