문제 정의
사용자가 콘솔에 네 개의 정수를 입력하면, 입력된 값들 중 가장 큰 수(최댓값)와 가장 작은 수(최솟값)를 찾아 출력하는 프로그램을 작성해 보겠습니다.
해결 방법
최댓값과 최솟값을 계산하기 위해 if 조건문을 활용합니다. 첫 번째 입력값을 기준값으로 설정한 뒤, 나머지 값들을 하나씩 비교하면서 더 큰 값이나 더 작은 값이 나타날 때마다 기준값을 갱신하는 방식입니다.
최댓값과 최솟값을 찾는 핵심 로직은 다음과 같습니다.
if(minno>q) // 1번째와 2번째 숫자 비교 minno=q; else if(maxno<q) maxno=q; if(minno>r) // 1번째와 3번째 숫자 비교 minno=r;
프로그램 1: 네 개의 정수 비교하기
사용자로부터 네 개의 정수를 입력받아 최댓값과 최솟값을 구하는 전체 코드입니다.
#include<stdio.h>
int main(){
int minno,maxno,p,q,r,s;
printf("enter any four numbers:");
scanf("%d%d%d%d",&p,&q,&r,&s);
minno=p;
maxno=p;
if(minno>q) // 1번째와 2번째 숫자 비교
minno=q;
else if(maxno<q)
maxno=q;
if(minno>r) // 1번째와 3번째 숫자 비교
minno=r;
else if(maxno<r)
maxno=r;
if(minno>s) // 1번째와 4번째 숫자 비교
minno=s;
else if(maxno<s)
maxno=s;
printf("Largest number from the given 4 numbers is:%d\n",maxno);
printf("Smallest numbers from the given 4 numbers is:%d",minno);
return 0;
}실행 결과
enter any four numbers:34 78 23 12 Largest number from the given 4 numbers is:78 Smallest numbers from the given 4 numbers is:12
프로그램 2: 배열에서 최댓값과 최솟값 찾기
다음 프로그램은 배열에 저장된 여러 개의 요소 중에서 가장 작은 값과 가장 큰 값을 찾습니다. 반복문(for)을 사용하면 입력받을 요소의 개수를 자유롭게 지정할 수 있어 더욱 유연하게 활용할 수 있습니다.
#include<stdio.h>
int main(){
int a[50],i,num,large,small;
printf("Enter the number of elements :");
scanf("%d",&num);
printf("Input the array elements :\n");
for(i=0;i<num;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<num;++i){
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("small= %d\n",small);
printf("large= %d\n",large);
return 0;
}실행 결과
Enter the number of elements :8 Input the array elements : 1 2 6 4 8 9 3 9 small= 1 large= 9
정리
이처럼 조건문만으로도 소수의 숫자를 비교할 수 있고, 배열과 반복문을 결합하면 임의의 개수를 가진 데이터에서도 손쉽게 최댓값과 최솟값을 구할 수 있습니다. 두 방식 모두 첫 번째 값을 초기 기준값으로 설정하고 이후 값들과 순차적으로 비교한다는 점에서 동일한 원리를 사용합니다.