-
[C++] find_max_n_min.cpp 최댓값, 최솟값 구하는 프로그램(배열 활용)C++/clone code 2022. 5. 23. 15:40
[프로그램]
1. 사용자로부터 배열의 크기를 입력받는다.
2. 앞서 입력받은 배열의 크기만큼 정수를 입력받는다.
3. 값들 중에서 최댓값, 최솟값을 구한다.
** 일반적인 방식, 함수를 사용한 방식 두 가지로 구현하기
[일반 방식]
#include <iostream> using namespace std; const int SIZE = 50; //배열의 크기를 기호상수로 선언 int main(){ int array[SIZE]; //50 int max; int min; int size; cout << "\n\n배열의 크기 입력: "; cin >> size; //배열의 크기 입력 // Input array elements cout << "\n" << size << "개의 정수를 입력하세요: "; // 배열의 크기까지 입력 반복 for (int i = 0; i < size; i++) cin >> array[i]; // 최대, 최솟값 0으로 가정 max = array[0]; min = array[0]; // 반복문을 이용해 모든 배열의 원소를 확인해서 최대, 최솟값 찾기 for (int i = 0; i < size; i++) { if (array[i] > max) max = array[i]; if (array[i] < min) min = array[i]; } cout << "\n===결과==="; cout << "\n최댓값 = " << max << "\n"; cout << "최솟값 = " << min; cout << "\n=========="; return 0; }
[알고리즘]
1. 최댓값, 최솟값을 배열의 0번째 값으로 가정한 뒤, 모든 배열의 원소와 비교한다.
for (int i = 0; i < size; i++){ if (array[i] > max) max = array[i]; if (array[i] < min) min = array[i]; }
[함수 이용]
#include <iostream> using namespace std; const int SIZE = 50; // 배열의 크기를 기호상수로 선언 int find_max(int a[], int n) { int max; max = a[0]; // 배열의 첫 번째 원소가 최댓값이라고 가정 for (int i = 0; i < n; i++) { if (a[i] > max) max = a[i]; } return max; } int find_min(int a[], int n) { int min; min = a[0]; for (int j = 0; j < n; j++) { if (a[0] < min) min = a[0]; } return min; } int main() { // 변수 선언 int array[50]; int size; int max; int min; cout << "\n\n배열의 크기 입력: "; cin >> size; //배열의 크기 입력 // 배열의 크기까지 입력 반복 for (int i = 0; i < size; i++) cin >> array[i]; // 함수 호출 max = find_max(array, size); min = find_min(array, size); // 출력 cout << "\n===결과==="; cout << "\n최댓값 = " << max << "\n"; cout << "최솟값 = " << min; cout << "\n=========="; return 0; }
출력 결과
'C++ > clone code' 카테고리의 다른 글
[C++] 계좌 잔액 조회하기.cpp (객체와 클래스에 대한 이해) (0) 2022.06.28 [C++] desk_lamp.cpp (객체와 클래스에 대한 이해) (0) 2022.06.28 [C++] sum_matrix.cpp 3x3 행렬 덧셈 프로그램 (0) 2022.05.23 [C++] 2차원 배열의 이해(two dimensional array) (0) 2022.05.23 [C++] average.cpp 배열을 활용한 평균 계산 (0) 2022.05.22