C# 기본 - 01
C#
- .Net Framework에서 실행되는 Microsoft 에서 만든 객체 지향 프로그래밍 언어
- C 계열에 뿌리를 두고 있으며 C++ 및 Java와 유사함
○ 값(문자열) 출력하기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study_01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
}
Console.ReadLine을 통해 사용자가 Enter를 칠때까지 콘솔 창이 띄워진다.
출력하는 함수로는 WriteLine과 Write 두 가지가 있으나 차이점은 WriteLine은 한 줄 씩 출력된다는 점이다.
○ 주석
C#의 주석은 // 를 통해 처리한다.
여러줄인 경우에는 /* */ 로 처리한다.
○ 변수 선언
데이터 타입 변수명 = 값
string name = "John";
Console.Write(name);
int myNum;
myNum = 15;
Console.Write(myNum);
< 데이터 타입 >
int , long , float , double , bool , char , string
long 타입은 int 보다 작은 정수를 저장한다. 값은 L로 끝나야한다.
float은 F , double은 D로 값을 끝내야한다.
double이 float보다 더 정밀함 >> 주로 사용
const int MyNum = 15;
myNum = 20; //error
const 를 사용하면 상수 처리가 되어 기존 값이 변경되지 않는다.
○ 데이터 타입 변환
한 데이터 타입의 값을 다른 타입에 할당하는 것
1. 암시적 캐스팅( 자동 ) >> 더 작은 유형을 더 큰 유형 크기로 변환
char -> int -> long -> float -> double
int myInt = 9;
double myDouble = myInt;
Console.Write(myInt); // Outputs 9
Console.Write(myDouble); // Outputs 9
2. 명시적 캐스팅 (수동) >> 더 큰 유형을 더 작은 크기 유형으로 변환
double -> float -> long -> int -> char
double myDouble = 9.78;
int myInt = (int) myDouble;
Console.Write(myDouble); // Outputs 9.78
Console.Write(myInt); // Outputs 9
3. Convert.To~
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
○ 사용자의 입력 받기
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
Console.ReadLine() 을 통해 입력을 받는다.
입력 받은 내용은 string으로 간주하기 때문에 int형식으로 받고자 한다면,
int age = Convert.ToInt32(Console.ReadLine());
위와 같이 Convert.ToInt32를 사용하여 데이터 타입을 변환시켜줘야 한다.
○ 연산자
사칙 연산은 다른 언어와 동일하다. ( + , - , * , / , % )
++ : 1씩 증가
-- : 1씩 감소
== , != : 같다/같지않다
논리연산자 : && , || , !
○ Math
Math.Max( a, b) : a와 b 중 큰 값
Math.Min( a, b) : a와 b 중 작은 값
Math.Sqrt( a ) : a의 제곱근
Math.Abs( a ) : a의 절대값
Math.Round( a ) : a의 가장 가까운 정수 >> 9.99 -> 10
○ 문자열
txt는 문자열을 담고있는 변수
txt.Length : 문자열의 길이
txt.ToUpper() : 대문자로 변환
txt.ToLower() : 소문자로 변환
string.Concat( a , b ) 또는 a+b : 문자열 a와 b를 연결
문자열 보간
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);
txt.IndexOf("a") : 문자열 txt에서 특정문자 a 의 인덱스 위치 찾기
txt.Substring( int ) : 문자열 txt 에서 지정된 인덱스(int) 로 부터 시작하는 문자 추출
백슬래시( \ ) 이스케이프 문자는 특수문자를 문자열 문자로 변환함
string txt = "We are the so-called "Vikings" from the north.";
string txt = "We are the so-called \"Vikings\" from the north.";
\n : 줄바꿈
\t : 탭
\b : 백스페이스
○ If Else
if ( 조건문1 )
{
조건문 1이 True 일 때
}
else if ( 조건문2 )
{
조건문 2가 True 일때
}
else
{
두 조건에 만족하지 않을 때
}
삼항 연산자
변수 = ( 조건문) ? True일때 : False일때
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);
○ Switch
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
case 대신 default : 를 통해 앞선 case에 해당하지 않는 경우 실행할 코드를 지정할 수 있다.
○ While
while ( 조건문 )
{
실행문
}
Do/While 루프
조건이 True인지를 확인하기 전에 코드를 실행 한 뒤에 조건이 true인 동안 루프 반복함
즉 조건이 거짓이더라도 루프가 적어도 한번은 실행됨
do
{
// code block to be executed
}
while (condition);
○ For
for ( 명령문(변수 설정) : 조건문 : 조건 true면 실행 )
{
실행문
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
○ For each
배열(리스트) 의 모든 요소 반환
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
○ 배열
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right away
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements without specifying the size
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements, omitting the new keyword, and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
배열의 길이 : array.Length
Foreach 루프 사용
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
배열 정렬 : Array.Sort(array_name)
< 다차원 배열 >
2차원 배열
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
요소에 접근시 numbers[0,2] 로 접근
foreach를 통한 루프 >> 동일하게 하나만 필요