C Program to Find the Smallest element in an Array.

Problem Statement: Given an array of integers, write a C program to find the smallest element in the array. 

Example:

Input: arr[] = {12, 45, 67, 32, 90, 3}
Output: Smallest element: 3

Input: arr[] = {11, 15, 17, 22, 9, 10}
Output: Smallest element: 9

Algorithm to Find Smallest Element in an Array.

Below are the steps that we need to follow:

Step 1: Initialize a variable min to store the smallest element and set it to the first element of the array.
Step 2: Input the size of the array and create an array arr of that size.
Step 3: Input the elements of the array arr.
Step 4: Traverse through the array from the second element to the last element.
  • If the current element is smaller than min, update the value of min to the current element.
Step 5: Print the value of min.

Program to Find the Smallest Element from Given Array.

//C program to find smallest element of the array
#include <stdio.h>

int main() {
    int n, min;

    printf("Enter the size of the array: ");
    scanf("%d", &n);

    int arr[n]; 

    printf("Enter the elements of the array:\n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Initialize 'min' to the first element of the array.
    min = arr[0];

    // Traverse to find the smallest element.
    for (int i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }

    printf("Smallest element: %d\n", min);

    return 0;
}
Output:
Enter the size of the array: 5
Enter the elements of the array:
12 3 9 10 22
Smallest element: 3

Time Complexity: The time complexity of this code is O(n) since we need to traverse through the entire array once to find the smallest element.

Space Complexity: The space complexity of this code is O(1) because we are not using any extra space to find the minimum element.

Related articles:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS