방명록
- C# #2 조건문과 반복문2023년 08월 14일 19시 29분 34초에 업로드 된 글입니다.작성자: noun06
내배캠 TIL 12
조건문
- 프로그램이 특정 조건에 따라 동작을 수행하도록 하는 제어 구조.
- if - else 문
if (조건식1) { // 조건식1이 참일 경우 실행할 코드 } else if (조건식2) { // 조건식2가 참일 경우 실행할 코드 } else { // 모든 조건식이 거짓일 경우 실행할 코드 }
- 중첩 조건문 : 하나 이상의 조건문이 다른 조건문 안에 포함되어있는 구조.
int age = 25; bool isStudent = true; if (age >= 18) { if (isStudent) { Console.WriteLine("성인 학생입니다."); } else { Console.WriteLine("성인입니다."); } } else { Console.WriteLine("미성년자입니다."); }
- switch - case 문 : 하나의 변수나 식의 값에 따라 여러가지 케이스 중 하나를 선택하여 실행을 결정할 때 사용.
switch (변수나 식) { case 값1: // 값1이 나온 경우 실행되는 코드 break; case 값2: // 값2가 나온 경우 실행되는 코드 break; // ... default: // 모든 case문에 해당하지 않는 경우 실행되는 코드 break; } int dayOfWeek = 3; switch (dayOfWeek) { case 1: Console.WriteLine("월요일"); break; case 2: Console.WriteLine("화요일"); break; case 3: Console.WriteLine("수요일"); break; default: Console.WriteLine("일주일 중에 어느 날인지 모르겠습니다."); break; }
- 삼항 연산자 : 조건식의 결과에 따라 두 값을 선택하는 연산자.(if 문의 간결한 형태)
(조건식) ? 참일 경우 값 : 거짓일 경우 값; int currentExp = 10; int requiredExp = 30; string result = (currentExp <= requiredExp) ? "레벨업 불가능" : "레벨업 가능";
조건문 실습
- 홀수 / 짝수 구분하기
//홀수 짝수 구분하기 Console.Write("숫자를 입력하세요: "); int num = int.Parse(Console.ReadLine()); if(num % 2 == 0) { Console.WriteLine("짝수입니다."); } else { Console.WriteLine("홀수입니다."); }
- 등급 출력(switch)
//등급 출력 Console.Write("점수를 입력하세요: "); int score = int.Parse(Console.ReadLine()); string rank = ""; switch (score / 10) // 첫번째 자리 수를 기준으로 케이스 나눔 { case 10: case 9: rank = "Diamond"; break; case 8: rank = "Platinum"; break; case 7: rank = "Gold"; break; case 6: rank = "Silver"; break; default: rank = "Bronze"; break; } Console.WriteLine("플레이어의 등급은 " + rank);
- 로그인 프로그램
//로그인 string myID = "noun06"; string myPW = "1234"; Console.Write("ID를 입력하세요: "); string id = Console.ReadLine(); Console.Write("비밀번호를 입력하세요: "); string pw = Console.ReadLine(); if (myID == id && myPW == pw) { Console.Write("로그인 되었습니다."); } else { Console.Write("로그인 실패!"); }
- 알파벳 판별 프로그램
//알파벳 판별 Console.Write("글자를 입력하세요: "); char word = Console.ReadLine()[0]; // string의 첫번째 인덱스만을 읽음으로 char 자료형 사용. if ((word >= 'a' && word <= 'z') || (word >= 'A' && word <= 'Z')) { Console.WriteLine(word + " 는 알파벳 입니다!"); } else { Console.WriteLine(word + " 는 알파벳이 아닙니다."); }
반복문
- 프로그램이 특정 조건을 만족하는 동안 작업을 반복 실행하는 제어 구조.
- for 문 : 주로 특정 범위의 값을 반복하거나 특정 횟수만큼 반복할 때 사용. (가독성이 좋음)
for (초기식; 조건식; 증감식) { // 조건식이 참인 경우 실행되는 코드 } for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
- while 문 : 주로 특정 조건이 만족될 때까지 반복이 필요한 경우에 사용. (반복 횟수를 미리 알 수 없는 경우 적합)
while (조건식) { // 조건식이 참인 경우 실행되는 코드 } int i = 0; //for의 초기식 while (i < 10) { Console.WriteLine(i); i++; //for의 증감식 }
- do - while 문 : 먼저 코드를 실행한 후 조건을 검사하여 조건이 참인 경우 반복 실행.
do { // 조건식이 참인 경우 실행되는 코드 } while (조건식); int count = 0; do { Console.WriteLine("카운트: " + count); count++; } while (count < 5);
- foreach 문 : 배열이나 컬렉션에 대한 반복문에 사용.
foreach (자료형 변수 in 배열 또는 컬렉션) { // 배열 또는 컬렉션의 모든 요소에 대해 반복적으로 실행되는 코드 } string[] inventory = { "검", "방패", "활", "화살", "물약" }; foreach (string item in inventory) { Console.WriteLine(item); }
- 중첩반복문 : 하나 이상의 반복문이 다른 반복 안에 포함되어있는 구조.
for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { Console.WriteLine("i: {0}, j: {1}", i, j); } }
- break : 반복문의 실행을 즉시 중지하고 종료하는 역할.
- continue : 해당 반복 회차의 실행을 중단하고 다음 회차로 건너뛰는 역할.
for (int i = 1; i <= 10; i++) { if (i == 5) { break; // i가 5일 때 반복문 종료 } Console.WriteLine(i); } for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // 짝수일 때 다음 회차로 건너뛰기 } Console.WriteLine(i); }
반복문 실습
- 가위바위보
//가위바위보 string[] choices = { "가위", "바위", "보" }; string myInput = ""; string comInput = choices[new Random().Next(0, 3)]; //배열 choices 중 랜덤 값 선택 while (myInput != comInput) { Console.Write("가위, 바위, 보 중 하나 선택 : "); myInput = Console.ReadLine(); if (myInput == "가위" && comInput == "보" || myInput == "바위" && comInput == "가위" || myInput == "보" && comInput == "가위") { Console.WriteLine("플레이어 승리!"); } else if (myInput == comInput) { Console.WriteLine("비겼습니다."); } else { Console.WriteLine("컴퓨터 승리!"); } }
- 숫자 맞추기
//숫자맞추기 int num = new Random().Next(1, 101); // 1~100 까지 랜덤한 숫자 할당 int myNum = 0; int numCount = 0; while(num != myNum) { Console.Write("숫자를 입력하세요 : "); myNum = int.Parse(Console.ReadLine()); numCount++; if(num > myNum) { Console.WriteLine("업"); } else if(num < myNum) { Console.WriteLine("다운"); } else { Console.WriteLine("맞췄습니다."); Console.WriteLine("시도 횟수: " + numCount); } }
내일은 반복문과 배열에 대해서 완벽하게 이해하고 다음 메서드, 클래스를 이어나가면서 공부할 예정이다.
'C#' 카테고리의 다른 글
C# #5 클래스, 객체, 상속, 다형성 (0) 2023.08.16 C# #4 메서드와 구조체 (0) 2023.08.15 C# #3 배열과 컬렉션 (0) 2023.08.15 C# #1 프로그래밍 기본 요소, 변수, 자료형, 연산자와 문자열 처리 (0) 2023.08.14 C# #0 - 간단한 예습 (0) 2023.08.11 다음글이 없습니다.이전글이 없습니다.댓글