C program to traverse each element of an array and print its value
#include <stdio.h>
int main() {
int myArray[] = {1, 2, 3, 4, 5}; // Example array
int length = sizeof(myArray) / sizeof(myArray[0]); // Calculate array length
printf("Array elements: ");
for (int i = 0; i < length; i++)
{
printf("myArray[%d]=%d \n ",i, myArray[i]); // Print each element
}
printf("\n"); // Newline for better formatting
return 0;
}
Write a C program to perform array insertion
#include <stdio.h>
void insert(int arr[], int *n, int pos, int val) {
// Shift elements to the right
for (int i = *n; i > pos; i--)
arr[i] = arr[i - 1];
// Insert val at the specified position
arr[pos] = val;
// Increase the current size
(*n)++;
}
int main() {
int arr[7] = {10, 20, 30, 40, 50};
int n = 5;
int pos = 3;
int val = 25;
// Insert the value at the specified position
insert(arr, &n, pos, val);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
C program to perform array deletion.
#include <stdio.h>
void del(int arr[], int *n, int key) {
// Find the element
int i = 0; int j;
while (arr[i] != key) i++;
// Shifting the right side elements one
// position towards left
for (j = i; j < *n - 1; j++)
{
arr[i] = arr[i + 1];
}
// Decrease the size
(*n)--;
}
int main()
{
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
// Delete the key from array
del(arr, &n, key);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
Write a C program to sort an array of five elements.
#include <stdio.h>
// Bubble sort implementation
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = { 2 ,6, 1, 5, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Perform bubble sort
bubbleSort(arr,n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}