C Program to implement a dynamic array, find the smallest and largest element of the array
ALGORITHM :
Step 1: Start
Step 2: Create a class DynamicArray.
Step 3: Declare an empty list variable (array) inside the class.
Step 4: Define a method append(self, element) to add elements to the list.
Step 5: Define a method get_smallest_element(self) to find the smallest element in the list using min().
Step 6: Define a method get_largest_element(self) to find the largest element in the list using max().
Step 7: Input the elements to add to the dynamic array.
Step 8: Create an object (arr) of the DynamicArray class.
Step 9: Call the append method for each element to add it to the array.
Step 10: Call the get_smallest_element method to find the smallest element and store it in a variable (smallest).
Step 11: Call the get_largest_element method to find the largest element and store it in a variable (largest).
Step 12: Display the smallest and largest elements.
Step 13: End
SOURCE CODE :
#include <stdio.h>
#include <stdlib.h>
// Function to find the smallest and largest element of the array
void findMinMax(int arr[], int size, int min, int max) {
min = arr[0];
max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size <= 0) {
printf("Invalid array size. Please enter a positive integer.\n");
return 1;
}
int *arr = (int *)malloc(size * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
int min, max;
findMinMax(arr, size, &min, &max);
printf("Smallest element: %d\n", min);
printf("Largest element: %d\n", max);
// Free the dynamically allocated memory
free(arr);
return 0;
}
OUTPUT :
Enter the size of the array: 5
Enter the elements of the array:
32 56 12 78 43
Smallest element: 12
Largest element: 78
No comments:
Post a Comment