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; }
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:
No comments:
Post a Comment