C# 공부 #1

jinatra·2022년 8월 12일

C#

목록 보기
1/2
post-thumbnail

1. 조건부 연산자

C#에서 조건을 바로바로 판단할 때 사용

조건 ? A : B

조건 A가 참이면 A,
조건 B가 참이면 B 반환

실습

## 비즈니스 규칙 (문제)
사용자가 55 를 초과하는 수준을 가진 관리자인 경우 다음과 같은 메시지가 표시됩니다.
Welcome, Super Admin user.

사용자가 55 이하의 수준을 가진 관리자인 경우 다음과 같은 메시지가 표시됩니다.
Welcome, Admin user.

사용자가 20 이상의 수준을 가진 매니저인 경우 다음과 같은 메시지가 표시됩니다.
Contact an Admin for access

사용자가 20 미만의 수준을 가진 매니저인 경우 다음과 같은 메시지가 표시됩니다.
You do not have sufficient privileges.

사용자가 관리자 또는 매니저가 아닌 경우 다음과 같은 메시지가 표시됩니다.
You do not have sufficient privileges.
## My Answer
string permission = "Manager";
int level = 25;

if (permission.Contains("Admin") || permission.Contains("Manager"))
{
    if (permission=="Admin")
    {
        Console.WriteLine((level > 55 ? "Welcome, Super Admin user." : "Welcome, Admin user."));
    }
    else
    {
        Console.WriteLine((level < 20) ? "You do not have sufficient privileges." : "Contact an Admin for access.");
    }
}
else
{
    Console.WriteLine("You do not have sufficient privileges.");
}
## MS answer
string permission = "Admin|Manager";
int level = 53;

if (permission.Contains("Admin"))
{
    if (level > 55)
    {
        Console.WriteLine("Welcome, Super Admin user.");
    }
    else
    {
        Console.WriteLine("Welcome, Admin user.");
    }
}
else if (permission.Contains("Manager"))
{
    if (level >= 20)
    {
        Console.WriteLine("Contact an Admin for access.");
    }
    else
    {
        Console.WriteLine("You do not have sufficient privileges.");
    }
}
else
{
    Console.WriteLine("You do not have sufficient privileges.");
}

내 코드와 마이크로소프트 공식 풀이랑 좀 다르긴 한데, 그래도 큰 차이는 없는 듯 하다.
알아두면 유용하게 쓸 수 있을 듯


2. switch-case문

조건에 따라 각각 다른 분기점으로 처리하는 방법
if-else랑 잘 구분해서 쓰면 효율적일듯

switch()
{
	case 조건1:
    	처리1;
        break;
        
    case 조건2:
    	처리2;
        break;
        
    default:
    	디폴트처리값:
        break;
        
}

실습

## 질문: 아래 if-else문을 switch-case문으로 변경
// SKU = Stock Keeping Unit
string sku = "01-MN-L";

string[] product = sku.Split('-');

string type = "";
string color = "";
string size = "";

if (product[0] == "01")
{
    type = "Sweat shirt";
} else if (product[0] == "02")
{
    type = "T-Shirt";
} else if (product[0] == "03")
{
    type = "Sweat pants";
}
else
{
    type = "Other";
}

if (product[1] == "BL")
{
    color = "Black";
} else if (product[1] == "MN")
{
    color = "Maroon";
} else
{
    color = "White";
}

if (product[2] == "S")
{
    size = "Small";
} else if (product[2] == "M")
{
    size = "Medium";
} else if (product[2] == "L")
{
    size = "Large";
} else
{
    size = "One Size Fits All";
}

Console.WriteLine($"Product: {size} {color} {type}");
## My Answer
// SKU = Stock Keeping Unit
string sku = "01-MN-L";

string[] product = sku.Split('-');

string type = "";
string color = "";
string size = "";

switch(product[0])
{
    case "01":
        type = "Sweat shirt";
        break;
    case "02":
        type = "T-shirt";
        break;
    case "03":
        type = "Sweat pants";
        break;
    default:
        type = "Other";
        break;
}

switch (product[1])
{
    case "BL":
        color = "Black";
        break;
    case "MN":
        color = "Maroon";
        break;
    default:
        color = "White";
        break;
}

switch (product[2])
{
    case "S":
        size = "Small";
        break;
    case "M":
        size = "Medium";
        break;
    case "L":
        size = "Large";
        break;
    default:
        size = "One Size fits all";
        break;
}

Console.WriteLine($"Product: {size} {color} {type}");

MS 공식 답이랑 큰 차이 없다.
이거 언제 유용하게 쓰일까..?
if-else로 에지간한거 다 커버될 듯 한데 검색해봐야겠다.


3. for문

for (시작값(초기화); 조건; 증감)
{
	로직;
}

친절하게 설명해주는 python과는 조금 다르게 그냥 한줄에 다 때려박아버린다.

예를 들어 정수 0부터 시작해서 5까지 하나씩 증가하고 각 값을 출력하고 싶으면 아래처럼 하면 된다.

for (int i = 0; i <= 5; i++)
{
	Console.WriteLine(i);
}

## 10이전까지 2씩 증가
for (int i = 0; i <= 10; i+=2)
{
	Console.WriteLine(i);
}

실습

FizzBuzz 과제

FizzBuzz 규칙:

  • 1에서 100사이의 값을 한 줄에 하나씩 출력합니다.
  • 현재 값을 3으로 나눌 경우 숫자 옆에 Fizz라는 용어를 인쇄합니다.
  • 현재 값을 5로 나눌 경우 숫자 옆에 Buzz라는 용어를 인쇄합니다.
  • 현재 값이 3 및 5 모두인 경우 숫자 옆에 FizzBuzz라는 용어를 인쇄합니다.
## 출력 예시

1
2
3 - Fizz
4
5 - Buzz
6 - Fizz
7
8
9 - Fizz
10 - Buzz
11
12 - Fizz
13
14
15 - FizzBuzz
16
17
18 - Fizz
19
20 - Buzz
21 - Fizz
22
.
.
.
## My Answer
for (int i = 1; i <= 20; i++)
{
    if ((i % 3 == 0) || (i % 5 == 0))
    {
        if ((i % 3 == 0) && (i % 5 == 0))
        {
            Console.WriteLine($"{i} - FizzBuzz");
        }
        else if (i % 3 ==0)
        {
            Console.WriteLine($"{i} - Fizz");
        }
        else
        {
            Console.WriteLine($"{i} - Buzz");
        }
    }
    else
    {
        Console.WriteLine(i);
    }
}
## MS Answer
for (int i = 1; i < 101; i++)
{
    if ((i % 3 == 0) && (i % 5 == 0))
        Console.WriteLine($"{i} - FizzBuzz");
    else if (i % 3 == 0)
        Console.WriteLine($"{i} - Fizz");
    else if (i % 5 == 0)
        Console.WriteLine($"{i} - Buzz");
    else
        Console.WriteLine($"{i}");
}

MS풀이가 내꺼보다 더 간결해보인다.
나는 굳이 쓸 필요 없는 이중if문을 썼는데, MS문은 if문 1번 로직에서 이미 이중조건을 처리해버려서 뒤에서는 나머지 조건만 챙기면 되는것.
나는 무슨 생각이었는지 괜히 그 안에서 한번 더 돌렸다.

쓸데없는 것을 줄이려고 항상 생각하기!


while, do-while문

while문

while(조건)
{
	반복처리로직;
}

do-while문

do
{
	반복처리로직;
} while (조건)

차이

  • while문 - 처음 시작할 때 조건이 참인 경우에 로직 시작
  • do-while문 - 조건 상관없이 우선 로직 한번 실행한 후 조건 판단 시작

continue 사용

## 예시
Random random = new Random();
int current = random.Next(1, 11);

do
{
    current = random.Next(1, 11);
    if (current >= 8) continue;
    Console.WriteLine(current);
} while (current != 7);

예시 설명
1. 임의로 난수 하나 뽑고
2. 해당 숫자가 7이 아닐 경우 (while문 조건)
3. 8보다 크면 콘솔 출력
4. 7이면 종료

profile
으악

0개의 댓글