Finding the maximum and minimum values in an array is a common task in C programming that helps you understand array traversal and basic comparisons. Here’s how you can implement a program to accomplish this.
Example: Find Maximum and Minimum in an Array
In this example, we will write a program that allows the user to input a specific number of integers into an array and then finds and displays the maximum and minimum values.
C Program to Find Maximum and Minimum in an Array
Explanation:
Variable Declarations:
int n
: This variable holds the number of elements the user wants to input.int i
: Loop counter for iterating through the array.int arr[100]
: Declares an integer array of size 100 to store the elements.
Input for Array Size:
- The program prompts the user to enter the number of elements they want to analyze and stores this value in
n
.
- The program prompts the user to enter the number of elements they want to analyze and stores this value in
Input for Array Elements:
- A
for
loop is used to iterate from0
ton-1
, prompting the user to input each integer, which is stored in the arrayarr
.
- A
Finding Maximum and Minimum Values:
- The variables
max
andmin
are initialized to the first element of the array (arr[0]
). - A
for
loop is then used to traverse the array starting from the second element (i = 1
):- If the current element
arr[i]
is greater thanmax
, it updatesmax
. - If the current element
arr[i]
is less thanmin
, it updatesmin
.
- If the current element
- The variables
Output the Maximum and Minimum Values:
- Finally, the program prints the maximum and minimum values found in the array.
Sample Output:
Example 1:
Example 2:
Key Points:
- Array Traversal: The program demonstrates how to iterate through an array using a loop.
- Comparison Logic: Simple
if
statements are used to compare values and update the maximum and minimum values accordingly. - Input/Output: Standard input/output functions are employed to interact with the user.
Variations:
You can modify the program to:
- Handle larger arrays dynamically using dynamic memory allocation (with
malloc
). - Find the maximum and minimum in specific ranges of the array based on user input.
- Implement functions to encapsulate the logic for finding the maximum and minimum values, enhancing code modularity.
This program serves as a foundational exercise for understanding arrays, loops, and conditional statements in C programming.