#5. [백준_C언어] 2562번 : 최댓값

 

 입력코드 

#include <stdio.h>

main() {
	int narray[9];
	int max, i, j;

	for (i = 0; i < 9; i++) {
		scanf("%d", &narray[i]);
	}
	max = narray[0];

	for (i = 0; i < 9; i++){
		if (narray[i] > max)
			max = narray[i];
	}
	for (j = 0; j < 9; j++) {
		if (narray[j] == max)
			break;
	}

	printf("%d\n", max);
	printf("%d\n", j+1);
}

 

 코드설명 

배열과 반복문, 대입 이용하는 문제

#include <stdio.h>

main() {
	int narray[9];
	int max, i;

	scanf("%d", &max);

	for (i = 0; i < 9; i++) {
		if (narray[i] > max)
			max = narray[i];
	}
	printf("%d\n", max);
	printf("%d\n", i);
}

처음에는 이렇게 했다가 배열 안에 입력하는 게 안돼서 뭔가 잘못되었음을 느끼고

 

참고한 사이트

parkjinho.org/11-1-%EB%B0%B0%EC%97%B4%EC%9D%98-%EC%9D%B4%ED%95%B4%EC%99%80-%EB%B0%B0%EC%97%B4%EC%9D%98-%EC%84%A0%EC%96%B8-%EB%B0%8F-%EC%B4%88%EA%B8%B0%ED%99%94-%EB%B0%A9%EB%B2%95/

 

11-1. 배열의 이해와 배열의 선언 및 초기화 방법 » Park,Jinho » 자아개발 및 개인 PR

‘둘 이상의 변수를 모아 놓은 것’이 배열이며, 선언 방법부터 접근방법까지 일반적인 변수와 차이가 있다. 표 형태와 같이 많은 데이터를 저장하고 처리하는 경우에 유용하게 사용 할 수 있는

parkjinho.org

 

#include <stdio.h>

main() {
	int narray[9];
	int max, i;

	for (i = 0; i < 9; i++) {
		scanf("%d", &narray[i]);
		max = narray[0];

		if (narray[i] > max)
			max = narray[i];
	}
	printf("%d\n", max);
	printf("%d\n", i);
}

이렇게 해서 배열 안에는 입력할 수 있게 되었는데 최댓값이 출력되는 게 아니라 마지막 값이 출력되어서 

i=0일 때 조건을 만족하지 못해서 바로 그냥 출력되나 싶다가도 그러면 첫 번째 값이 출력돼야 하는 거 아닌가 생각했다.

#include <stdio.h>

main() {
	int narray[9];
	int max, i;

	for (i = 0; i < 9; i++) {
		scanf("%d", &narray[i]);
	}
		max = narray[0];

	for (i = 0; i < 9; i++){
		if (narray[i] > max)
			max = narray[i];
	}
	printf("%d\n", max);
	printf("%d\n", i);
}

반복문을 두 개로 나누어서 작성했더니 최댓값은 이제 제대로 출력되는데 몇 번째 숫자인지가 잘못 출력되었다.

배열에서 첫번째 인덱스가 0이어서 그런가 싶어서 1을 더해주었더니 그게 문제가 아니었나 보다.

 

찾아보니까 처음부터 max값을 어차피 자연수 값이어서 0으로 잡고 시작하는 분들이 많았는데 내가 원하는 풀이가 아니어서 찾아보다가 아예 index값을 새로운 변수로 지정하는 방법도 있었다.

#include <stdio.h>

int main() {
	int a = 0, num[9], index;

	for (int i = 0; i < 9; i++) {
		scanf("%d", &num[i]);
		if (a < num[i]) {
			a = num[i];
			index = i;
		}
	}
	printf("%d\n%d", a, index + 1);
}

 

 참고한 사이트

gururuglasses.tistory.com/72

 

백준 2562 ( 최대값 ) [ C programming ]

나: #include int main() { int a = 0, num[9], index; for (int i = 0; i < 9; i++) { scanf("%d",&num[i]); if (a < num[i]) { a = num[i]; index = i; } } printf("%d\n%d", a, index+1); } 완성된 코드는 위..

gururuglasses.tistory.com

pmj9.tistory.com/25

 

백준 2562번: 최댓값 [C언어]

문제 9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오. 예를 들어, 서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61 이

pmj9.tistory.com

 

 

 문제 출처 

www.acmicpc.net/problem/2562

 

2562번: 최댓값

9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오. 예를 들어, 서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61 이 주어

www.acmicpc.net