Chapter 7. 수많은 변수를 손쉽게 관리하려면, 배열
1. 변수가 많아지면 복잡해져요
<생략>
2. 배열
배열이란?
- Array (동)(명) 배열, 배열하다, 진열하다 ➡ (프로그래밍에서) 여러 변수가 한 줄로 줄을 서있다
문법: 자료형[] 배열명 = {요소1, 요소2, ...}; ex) int[] passcodeNumbers = {6, 2, 1, 9, 4, 7}; - 배열의 요소를 사용하려면?
: 배열에 있는 값(요소)에 접근할 때는 []을 사용하고 []안에는 숫자를 넣어 읽어올 위치를 지정한다. 첫번째 값을 읽어올 때는 [0], 두 번째 값을 읽어올 때는 [1] 이런 식으로.
즉, 첫 번째 숫자를 읽어올 때 1이 아니라 0을 사용한다는 것 - 사용자에게 입력받는 숫자를 배열에 저장하려면?
: 사용자가 입력하는 값은 실제로 입력을 받기 전에는 어떤 숫자인지 알 수 없다. 이런 경우 다음처럼 배열을 선언한다.
자료형[] 배열명 = new 자료형[요소의 개수];
다양한 종류의 배열 만들기
<생략>
안전하게 배열을 사용하려면?
<생략>
3. 컨테이너
- 컨테이너(container) = contain(담다) + -er: 무언가를 담고 있는 물체,
(프로그래밍에서) 다수의 데이터를 담을 수 있는 저장소 - 배열 외의 컨테이너
1. 리스트(list): 배열의 한계인 배열의 크기를 프로그램 실행 중에 바꿀 수 없는 문제를 해결한 컨테이너. 리스트는 언제라도 그 속에 들어가는 데이터의 개수를 변경할 수 있음
2. 딕셔너리(dictionary): 배열의 한계인 위치를 지정(인덱스)할 때 정수만 사용할 수 있는 문제를 해결한 컨테이너. 인덱스에 문자열을 사용할 수 있음.
기초문제
7-1. 배열을 사용해서 다음 코드를 바꾸세요.
double weight1 = double.Parse(Console.ReadLine());
double weight1 = double.Parse(Console.ReadLine());
double weight1 = double.Parse(Console.ReadLine());
Console.Write("첫 번째 무게: ");
Console.WriteLine(weight1);
Console.Write("두 번째 무게: ");
Console.WriteLine(weight2);
Console.Write("세 번째 무게: ");
Console.WriteLine(weight3);
나의 답
double[] weights = new double[3]; weights[0] = double.Parse(Console.ReadLine()); weights[1] = double.Parse(Console.ReadLine()); weights[2] = double.Parse(Console.ReadLine()); // Console.Write("첫 번째 무게: "); Console.WriteLine(weights[0]); Console.Write("두 번째 무게: "); Console.WriteLine(weights[1]); Console.Write("세 번째 무게: "); Console.WriteLine(weights[2]);
7-2. 배열을 사용해서 다음 코드를 바꾸세요.
string studentName1 = "홍길동";
string studentName2 = "김철수";
string studentName3 = "이영희";
Console.WriteLine(studentName1);
Console.WriteLine(studentName2);
Console.WriteLine(studentName3);
나의 답
string[] studentNames = { "홍길동", "김철수", "이영희" }; // Console.WriteLine(studentNames[0]); Console.WriteLine(studentNames[1]); Console.WriteLine(studentNames[2]);
7-3. 다음 코드에 버그가 있습니다. 찾아서 수정하세요.
<생략>
7-4. 다음 코드에서 (1), (2), (3)에 어떤 코드를 넣어야 할까요?
string[] subjects = { "국어", "영어", "수학" };
(1)
Console.Write(subjects[0]);
Console.WriteLine(" 점수를 입력하세요. ");
scores[0] = int.Parse(Console.ReadLine());
Console.Write(subjects[1]);
Console.WriteLine(" 점수를 입력하세요. ");
scores[1] = int.Parse(Console.ReadLine());
Console.Write(subjects[2]);
Console.WriteLine(" 점수를 입력하세요. ");
(2)
Console.Write(subjects[0]);
Console.Write("점수: ");
Console.WriteLine(scores[0]);
(3)
Console.Write("점수: ");
Console.WriteLine(scores[1]);
Console.Write(subjects[2]);
Console.Write("점수: ");
Console.WriteLine(scores[2]);
나의 답
(1) int[] scores = new int[3]; (2) scores[2] = int.Parse(Console.ReadLine()); (3) Console.Write(subjects[1]);
심화문제
7-1. 학생 명부 프로그램에 몸무게도 넣고 싶습니다. [코드7-4]를 수정해서 weights 배열을 추가하고 몸무게를 입력받으세요.
나의 답
Console.WriteLine("학생 숫자를 입력하세요"); int studentCount = int.Parse(Console.ReadLine()); int[] ages = new int[studentCount]; string[] names = new string[studentCount]; double[] heights = new double[studentCount]; double[] weights = new double[studentCount]; Console.WriteLine("몇 번째 학생의 정보를 추가할까요?"); int studentNumber = int.Parse(Console.ReadLine()); if (studentNumber >= 0 && studentNumber <= studentNumber - 1) { Console.WriteLine("나이를 입력하세요."); ages[studentNumber] = int.Parse(Console.ReadLine()); Console.WriteLine("이름을 입력하세요."); names[studentNumber] = Console.ReadLine(); Console.WriteLine("키를 입력하세요."); heights[studentNumber] = double.Parse(Console.ReadLine()); Console.WriteLine("몸무게를 입력하세요."); weights[studentNumber] = double.Parse(Console.ReadLine()); Console.Write(studentNumber); Console.WriteLine("번째 학생"); Console.Write("이름: "); Console.WriteLine(names[studentNumber]); Console.Write("나이: "); Console.WriteLine(ages[studentNumber]); Console.Write("키: "); Console.WriteLine(heights[studentNumber]); Console.Write("몸무게: "); Console.WriteLine(weights[studentNumber]); } else { Console.Write("0에서 "); Console.Write(studentCount - 1); Console.WriteLine("사이의 숫자를 입력하세요."); }
7-2. 국어, 영어, 수학, 과학, 사회 점수를 입력받아서 총점과 평균을 구하는 프로그램을 작성하세요.
(힌트: 점수에 배열을 사용하세요.)
나의 답
Console.WriteLine("| 7-2 |"); Console.WriteLine("국어, 영어, 수학, 과학, 사회 점수를 각각 입력하시오."); int[] scores = new int[5]; scores[0] = int.Parse(Console.ReadLine()); scores[1] = int.Parse(Console.ReadLine()); scores[2] = int.Parse(Console.ReadLine()); scores[3] = int.Parse(Console.ReadLine()); scores[4] = int.Parse(Console.ReadLine()); // int totalScores = scores[0] + scores[1] + scores[2] + scores[3] + scores[4]; int averageScores = totalScores / 5; Console.Write("총점: "); Console.WriteLine(totalScores); Console.Write("평균: "); Console.WriteLine(averageScores);
Chapter 8. 같은 코드를 여러 번 실행하려면, 반복문 while
1. 같은 코드를 여러 번 실행하고 싶어요
<생략>
2. ~하는 동안
- while (접) ~하는 동안, (프로그래밍에서) 조건이 참인 동안 코드를 실행
기본형: while(조건식) { 조건을 만족할 때만 실행 } - if와 while의 차이점: while은 {} 안의 코드를 실행한 다음에 다시 () 안의 조건식을 검사함. 따라서 while 안에 있는 조건식이 계속 참이라면 끊임없이 {} 사이의 코드를 실행한다.
3. 반복문 빠져나오기
- while(true): 조건식을 언제나 참으로 만들기 때문에 {} 안의 문장이 무한 반복됨.
- break (동)중단시키다, (프로그래밍에서) while문 안에서 break를 쓰면 즉시 while문의 반복을 끝냄.
- continue (동)계속하다, (프로그래밍에서) while문 안에서 continue를 쓰면 즉시 while문의 첫 문장부터 다시 실행함.
기초문제 220921 추가
8-1. 다음 코드가 while문을 사용하도록 바꿔보세요.
int[] scores = new int[5];
Console.Write(0);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[0] = int.Parse(Console.ReadLine());
Console.Write(1);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[1] = int.Parse(Console.ReadLine());
Console.Write(2);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[2] = int.Parse(Console.ReadLine());
Console.Write(3);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[3] = int.Parse(Console.ReadLine());
Console.Write(4);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[4] = int.Parse(Console.ReadLine());
Console.Write("총점은");
Console.Write(scores[0] + scores[1] + scores[2] + scores[3] + scores[4]);
Console.Write("점입니다.");
나의 답
int[] scores = new int[5]; int score = 0; while(score < 5) { Console.Write(score); Console.WriteLine("번째 과목의 성적을 입력하세요"); scores[score] = int.Parse(Console.ReadLine()); // score += 1; } // Console.Write("총점은"); Console.Write(scores[0] + scores[1] + scores[2] + scores[3] + scores[4]); Console.Write("점입니다.");
8-2. 다음 코드에서 (1), (2), (3)에 어떤 코드를 넣어야 할까요?
Console.WriteLine("수업을 몇 과목 들었습니까?");
int subjectCount = int.Parse(Console.ReadLine());
int[] scores = new int[subjectCount];
int index = 0;
int total = 0;
(1)
{
Console.Write(index);
Console.WriteLine("번째 과목의 성적을 입력하세요.");
scores[index] = int.Parse(Console.ReadLine());
total = total + scores[index];
(2)
}
Console.Write("평균은");
(3)
Console.WriteLine("점입니다.");
나의 답
(1) while (index < subjectCount) (2) index += 1; (3) Console.Write(total / subjectCount);
8-3. 다음 코드에는 세 개의 버그가 있습니다. 전부 찾아서 수정하세요.
<생략>
8-4. 다음 코드에서 11번 줄을 while(userInput != "끝") 대신 while(true)를 사용하게 바꾸세요.
(힌트: if와 break를 추가해야 합니다.)
string userInput = "";
while (userInput != "끝")
{
Console.WriteLine("아무 글자나 입력하세요. 끝내려면 '끝'을 입력하세요.");
userInput = Console.ReadLine();
Console.WriteLine(userInput);
}
나의 답
string userInput = ""; while (true) { Console.WriteLine("아무 글자나 입력하세요. 끝내려면 '끝'을 입력하세요"); userInput = Console.ReadLine(); Console.WriteLine(userInput); if (userInput == "끝") { break; }
심화문제
8-1. [코드 8-5]에서 비밀번호를 입력하는 부분을 while문을 사용하도록 수정하세요.
(힌트: 14~25번 줄까지만 수정하면 됩니다.)
나의 답
int[] passcodeNumbers = { 6, 2, 1, 9, 4, 7 }; int[] userInput = new int[6]; int index = 0; while (true) { Console.Write(index); Console.WriteLine("번째 숫자를 넣어주세요."); userInput[index] = int.Parse(Console.ReadLine()); index += 1; if (index == 6) { if (userInput[0] == passcodeNumbers[0] && userInput[1] == passcodeNumbers[1] && userInput[2] == passcodeNumbers[2] && userInput[3] == passcodeNumbers[3] && userInput[4] == passcodeNumbers[4] && userInput[5] == passcodeNumbers[5]) { Console.WriteLine("문이 열렸습니다"); break; } else { Console.WriteLine("비밀번호가 틀렸습니다."); index = 0; } } }
while문장 속 첫 문장부터 if문 전까지가 14~25번 줄이었는데 도무지 break;나 index = 0;을 추가하지 않으면 결과가 다르게 출력돼서 힌트에서 벗어나게 입력해부렀다 ,, 그래도 내가해냄ㅜ;
8-2. 먼저 총 학생 수를 입력받습니다. 그리고 각 학생마다 각각 국어, 영어, 수학 점수를 입력받습니다. 그 다음 입력받은 점수를 계산해서 각 학생의 총점과 평균을 구하는 프로그램을 작성하세요.
나의 답
Console.WriteLine("총 학생 수를 입력하세요."); int studentCount = int.Parse(Console.ReadLine()); int[] kScore = new int[studentCount]; int[] eScore = new int[studentCount]; int[] mScore = new int[studentCount]; int index = 0; while (index < studentCount) { Console.Write(index); Console.WriteLine("번째 학생의 국어 점수: "); kScore[index] = int.Parse(Console.ReadLine()); Console.Write(index); Console.WriteLine("번째 학생의 영어 점수: "); eScore[index] = int.Parse(Console.ReadLine()); Console.Write(index); Console.WriteLine("번째 학생의 수학 점수: "); mScore[index] = int.Parse(Console.ReadLine()); index += 1; } index = 0; while (index < studentCount) { int total = kScore[index] + eScore[index] + mScore[index]; Console.Write(index); Console.Write("번째 학생의 총점: "); Console.WriteLine(total); Console.Write(index); Console.Write("번째 학생의 평균: "); Console.WriteLine(total / 3); index += 1; }