프로그램 최적화 및 코드 완성
이제 작동하는 프로그램이 있으므로 가장 큰 요소와 가장 작은 요소를 모두 찾는 것을 단일 루프로 결합하여 최적화해 보겠습니다. 이렇게 하면 배열을 두 번이 아닌 한 번만 순회하면 되므로 더 효율적입니다.
main.c 파일을 열고 전체 내용을 다음 최적화된 버전으로 바꿉니다.
#include <stdio.h>
int main() {
// We'll declare an array with a maximum capacity of 50 elements
int array[50];
// Variables to store the size of the array and loop counter
int size, i;
// Variables to store the largest and smallest elements
int largest, smallest;
printf("Finding Largest and Smallest Elements in an Array\n");
printf("------------------------------------------------\n\n");
// Ask user for the size of the array
printf("Enter the size of the array (max 50): ");
scanf("%d", &size);
// Validate the input size
if (size <= 0 || size > 50) {
printf("Invalid array size. Please enter a size between 1 and 50.\n");
return 1;
}
// Get array elements from the user
printf("\nEnter %d elements of the array:\n", size);
for (i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &array[i]);
}
// Display the entered array
printf("\nThe array you entered is: [ ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("]\n\n");
// Initialize largest and smallest with the first element
largest = smallest = array[0];
// Find both the largest and smallest elements in a single pass
printf("Searching for largest and smallest elements...\n");
for (i = 1; i < size; i++) {
// Check for largest
if (array[i] > largest) {
largest = array[i];
printf("New largest found at position %d: %d\n", i + 1, largest);
}
// Check for smallest
if (array[i] < smallest) {
smallest = array[i];
printf("New smallest found at position %d: %d\n", i + 1, smallest);
}
}
// Display results
printf("\nResults:\n");
printf("- The largest element in the array is: %d\n", largest);
printf("- The smallest element in the array is: %d\n", smallest);
// Calculate and display the range
printf("- The range (difference between largest and smallest) is: %d\n", largest - smallest);
return 0;
}
이 최적화된 버전은 다음과 같습니다.
- 가장 큰 요소와 가장 작은 요소를 모두 찾기 위해 단일 루프를 사용하므로 프로그램의 효율성이 높아집니다.
largest와 smallest를 모두 배열의 첫 번째 요소로 초기화합니다.
- 범위 (가장 큰 값과 가장 작은 값의 차이) 에 대한 계산을 추가합니다.
최적화된 프로그램을 컴파일하고 실행해 보겠습니다.
gcc main.c -o main
./main
이전과 같이 배열 크기와 요소를 입력합니다. 예를 들어, 값 10, 25, 5, 17, 9 를 입력하면 다음과 유사한 출력이 표시됩니다.
Finding Largest and Smallest Elements in an Array
------------------------------------------------
Enter the size of the array (max 50): 5
Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9
The array you entered is: [ 10 25 5 17 9 ]
Searching for largest and smallest elements...
New largest found at position 2: 25
New smallest found at position 3: 5
Results:
- The largest element in the array is: 25
- The smallest element in the array is: 5
- The range (difference between largest and smallest) is: 20
이 최적화된 버전은 이전과 동일한 결과를 제공하지만 더 효율적이며 값의 범위에 대한 추가 정보를 포함합니다.
큰 배열로 작업할 때 이러한 효율성 향상은 계산 시간을 크게 줄일 수 있으며, 이는 프로그래밍에서 중요한 고려 사항입니다.