Create an array of size 10, find the largest value from the array.
Learn how to find the maximum value in an array using C programming
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This header provides essential input/output functions:
printf()for displaying outputscanf()for reading user input- Other standard I/O operations
๐น Step 2: Declare Array and Variables
int arr[10], i, max;
- arr[10]: Array to store 10 integer values
- i: Loop counter for array traversal
- max: Variable to store the maximum value
๐น Step 3: Input Elements in the Array
for(i = 0; i < 10; i++) {
printf("arr[%d]: ", i);
scanf("%d", &arr[i]);
}
- Prompts user to enter 10 values
- Stores each value in the array
- Uses
%dformat specifier for integers - Displays current index with
arr[%d]
๐น Step 4: Assume First Element as Maximum
max = arr[0];
- Initializes
maxwith first array element - Provides a starting point for comparison
- Common algorithm pattern for finding max/min
๐น Step 5: Compare and Find the Largest
for(i = 1; i < 10; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
- Starts loop from index 1 (since index 0 is already in max)
- Compares each element with current
max - Updates
maxif larger value is found - Implements linear search algorithm
๐น Step 6: Display the Result
printf("\nThe largest value in the array is: %d\n", max);
- Prints the final maximum value
- Uses
%dto format the integer output - Includes newline characters for clean formatting
๐งช Sample Output
Enter 10 elements:
arr[0]: 23
arr[1]: 45
arr[2]: 12
arr[3]: 99
arr[4]: 34
arr[5]: 67
arr[6]: 88
arr[7]: 54
arr[8]: 11
arr[9]: 76
The largest value in the array is: 99
๐ Key Concepts Covered
Array Declaration
Creating a fixed-size collection of elements with
int arr[size]Linear Search
Sequentially checking each element to find the maximum value
Conditional Logic
Using
if statements to compare valuesLoop Control
Using
for loops to traverse arraysVariable Initialization
Starting with a sensible default value (first element)
No comments:
Post a Comment