::template
#include <stdio.h>
#define MAX_SIZE 100
// Function to find the maximum element in an array
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[MAX_SIZE];
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter elements of the array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Find the maximum element in the array
int maximum = findMax(arr, size);
printf("The maximum element in the array is: %d\n", maximum);
return 0;
}
Explanation:
- #include <stdio.h>
: Includes the standard input/output library for input and output functions.
- #define MAX_SIZE 100
: Defines a constant MAX_SIZE
with a value of 100 to set the maximum size of the array.
- int findMax(int arr[], int size)
: Function that takes an array arr
and its size as parameters, and returns the maximum element in the array.
- int max = arr[0];
: Initializes a variable max
with the first element of the array.
- for (int i = 1; i < size; i++) { ... }
: Loops through the array starting from the second element to find the maximum element.
- if (arr[i] > max) { max = arr[i]; }
: Checks if the current element is greater than the maximum found so far. If yes, updates the max
variable.
- return max;
: Returns the maximum element after the loop ends.
- int main() { ... }
: The main function where the program execution begins.
- int arr[MAX_SIZE]; int size;
: Declares an array arr
of integers with a maximum size of MAX_SIZE
and an integer variable size
.
- printf("Enter the size of the array: "); scanf("%d", &size);
: Asks the user to input the size of the array and reads the input value into the size
variable.
- printf("Enter elements of the array:\n");
: Prints a message to prompt the user to input elements of the array.
- for (int i = 0; i < size; i++) { scanf("%d", &arr[i]); }
: Reads size
number of elements into the array arr
.
- int maximum = findMax(arr, size);
: Calls the findMax
function to find the maximum element in the array.
- printf("The maximum element in the array is: %d\n", maximum);
: Prints the maximum element found in the array.