C Program to Find the Largest element in an array.

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

Example:

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

Input: arr[] = {10, 9, 12, -6, 11}
Output: Largest element: 11

Algorithm to Find Largest Element from Array.

Below are the steps that we need to follow:

Step 1: Initialize a variable max to store the largest 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: Take the elements of the array arr from the user.
Step 4: Traverse through the array from the second element to the last element.
  • If the current element is greater than max, update the value of max to the current element.
Step 5: Print the value of max.

Program to Find the Largest Element of the Array.

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

int main() {
    int n, max;

    printf("Enter the size of the array: ");
    scanf("%d", &n);
    // Creating an array of size 'n'.
    int arr[n]; 

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

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

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

    printf("Largest element: %d\n", max);

    return 0;
}
Output:
Enter the size of the array: 6
Enter the elements of the array:
11 23 10 31 9 12
Largest element: 31

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

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

Similar 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