1. Program to Input and Print Elements of an Array Using Pointers
#include <stdio.h>
int main() {
int arr[5];
int *ptr = arr;
// Input elements
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", ptr + i);
}
// Print elements
printf("The elements of the array are:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
return 0;
}
2. Program to Find the Sum of All Elements in an Array Using a Pointer
#include <stdio.h>
int main() {
int arr[5];
int *ptr = arr;
int sum = 0;
// Input elements
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", ptr + i); // Use pointer arithmetic to store values
}
// Calculate sum
for (int i = 0; i < 5; i++) {
sum += *(ptr + i); // Use pointer arithmetic to access values
}
// Print the sum
printf("The sum of the elements is: %d\n", sum);
return 0;
}
3. Program to Reverse an Array Using Pointers
#include <stdio.h>
int main() {
int arr[5];
int *ptr = arr;
int temp;
// Input elements
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", ptr + i); // Use pointer arithmetic to store values
}
// Reverse the array
for (int i = 0; i < 2; i++) { // Only need to iterate half the array
temp = *(ptr + i);
*(ptr + i) = *(ptr + 4 - i); // Swap
*(ptr + 4 - i) = temp;
}
// Print the reversed array
printf("The reversed array is:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Use pointer arithmetic to access values
}
printf("\n");
return 0;
}
4. Program to Sort an Array Using Pointer-Based Bubble Sort
#include <stdio.h>
int main() {
int arr[5];
int *ptr = arr;
int temp;
// Input elements
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", ptr + i);
}
// Bubble sort
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (*(ptr + j) > *(ptr + j + 1)) { // Compare and swap
temp = *(ptr + j);
*(ptr + j) = *(ptr + j + 1);
*(ptr + j + 1) = temp;
}
}
}
// Print the sorted array
printf("The sorted array is:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Use pointer arithmetic to access values
}
printf("\n");
return 0;
}
5. Program to Find the Largest Element in an Array Using Pointers
#include <stdio.h>
int main() {
int arr[5];
int *ptr = arr;
int largest;
// Input elements
printf("Enter 5 elements:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", ptr + i); // Use pointer arithmetic to store values
}
largest = *ptr; // Assume the first element is the largest
// Find the largest element
for (int i = 1; i < 5; i++) {
if (*(ptr + i) > largest) {
largest = *(ptr + i); // Update largest if found a larger element
}
}
// Print the largest element
printf("The largest element is: %d\n", largest);
return 0;
}