입력과 출력 (Input and Output)
설명
입력과 출력은 프로그램에서 사용자와 상호작용하는 중요한 부분입니다. C#에서는 Console 클래스를 사용하여 입력을 받고 출력을 할 수 있습니다.
입력 받기
•
Console.ReadLine 메서드를 사용하여 사용자의 입력을 문자열로 받을 수 있습니다.
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");
C#
복사
출력하기
•
Console.WriteLine 메서드를 사용하여 콘솔에 메시지를 출력할 수 있습니다.
Console.WriteLine("Hello, World!");
C#
복사
숫자 입력 받기
•
입력받은 문자열을 숫자로 변환하려면 int.Parse 또는 Convert.ToInt32 메서드를 사용할 수 있습니다.
Console.WriteLine("Enter a number:");
int number = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered: {number}");
C#
복사
반복문 (Loops)
설명
반복문은 특정 코드 블록을 여러 번 실행할 때 사용됩니다. C#에서 자주 사용되는 반복문은 for, while, do-while 문이 있습니다.
for 문
•
반복 횟수가 정해져 있을 때 주로 사용합니다.
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
C#
복사
while 문
•
조건이 참인 동안 반복합니다.
int j = 0;
while (j < 10)
{
Console.WriteLine(j);
j++;
}
C#
복사
do-while 문
•
조건을 나중에 평가하므로 코드 블록이 최소 한 번 실행됩니다.
int k = 0;
do
{
Console.WriteLine(k);
k++;
} while (k < 10);
C#
복사
조건문 (Conditional Statements)
설명
조건문은 특정 조건에 따라 코드 블록을 실행할 때 사용됩니다. 자주 사용되는 조건문은 if, else if, else 문이 있습니다.
if 문
•
조건이 참인 경우에만 실행됩니다.
int number = 5;
if (number > 0)
{
Console.WriteLine("Positive number");
}
C#
복사
else if 문
•
이전 조건이 거짓이고, 새로운 조건이 참인 경우에 실행됩니다.
int number = -5;
if (number > 0)
{
Console.WriteLine("Positive number");
}
else if (number < 0)
{
Console.WriteLine("Negative number");
}
C#
복사
else 문
•
모든 조건이 거짓인 경우에 실행됩니다.
int number = 0;
if (number > 0)
{
Console.WriteLine("Positive number");
}
else if (number < 0)
{
Console.WriteLine("Negative number");
}
else
{
Console.WriteLine("Zero");
}
C#
복사
배열 (Arrays)
설명
배열은 같은 데이터 타입의 여러 값을 저장할 수 있는 자료구조입니다.
배열 선언과 초기화
•
배열을 선언하고 초기화하는 방법은 다음과 같습니다.
int[] numbers = new int[5]; // 크기가 5인 정수 배열 선언
numbers[0] = 10; // 첫 번째 요소에 값 10 저장
numbers[1] = 20; // 두 번째 요소에 값 20 저장
// 배열 선언과 동시에 초기화
int[] numbers = { 10, 20, 30, 40, 50 };
C#
복사
배열 접근과 순회
•
배열의 모든 요소를 순회하는 방법입니다.
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
C#
복사
클래스 (Classes)
설명
클래스는 객체를 정의하는 데 사용되는 청사진입니다. 속성과 메서드를 포함할 수 있습니다.
클래스 정의와 사용
•
클래스 정의와 객체 생성 방법입니다.
class Person
{
public string Name;
public int Age;
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
// 클래스 사용 예제
Person person = new Person();
person.Name = "John";
person.Age = 30;
person.Introduce();
C#
복사
상속 (Inheritance)
설명
상속은 한 클래스가 다른 클래스의 특성과 메서드를 물려받는 것을 의미합니다. C#은 다중 상속을 지원하지 않습니다. 하나의 클래스만 상속받을 수 있습니다.
상속 예제
•
상속을 통해 부모 클래스의 메서드를 자식 클래스에서 사용할 수 있습니다.
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
// 상속 사용 예제
Dog dog = new Dog();
dog.Eat();
dog.Bark();
C#
복사
인터페이스 (Interfaces)
설명
인터페이스는 클래스나 구조체가 구현해야 하는 메서드와 속성의 정의를 포함합니다. C#에서는 인터페이스를 다중 상속할 수 있습니다.
인터페이스 정의와 구현
•
인터페이스를 정의하고 구현하는 방법입니다.
interface IAnimal
{
void MakeSound();
}
class Dog : IAnimal
{
public void MakeSound()
{
Console.WriteLine("Bark");
}
}
// 인터페이스 사용 예제
IAnimal animal = new Dog();
animal.MakeSound();
C#
복사
추상 클래스 (Abstract Classes)
설명
추상 클래스는 인스턴스화될 수 없으며, 상속을 통해서만 사용될 수 있습니다. 추상 메서드를 포함할 수 있습니다.
추상 클래스 정의와 구현
•
추상 클래스와 이를 상속받아 구현하는 방법입니다.
abstract class Animal
{
public abstract void MakeSound();
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
// 추상 클래스 사용 예제
Animal animal = new Dog();
animal.MakeSound();
C#
복사
가상 메서드 (Virtual Methods)
설명
가상 메서드는 자식 클래스에서 재정의할 수 있는 부모 클래스의 메서드입니다.
가상 메서드 정의와 재정의
•
가상 메서드를 정의하고 이를 재정의하는 방법입니다.
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
// 가상 메서드 사용 예제
Animal animal = new Dog();
animal.MakeSound();
C#
복사
랜덤 숫자 생성 (Random Number Generation)
설명
컴퓨터 프로그램에서 난수를 생성하는 방법입니다. C#에서는 Random 클래스를 사용하여 난수를 생성할 수 있습니다.
Random 클래스 사용
•
Random 클래스는 난수를 생성하는 데 사용됩니다. 객체를 생성한 후, Next 메서드를 사용하여 난수를 생성할 수 있습니다.
Random random = new Random();
int randomNumber = random.Next(); // 0과 int.MaxValue 사이의 난수 생성
int randomNumberInRange = random.Next(1, 101); // 1과 100 사이의 난수 생성
C#
복사
랜덤 숫자 생성 예제
•
다음은 Random 클래스를 사용하여 1부터 100 사이의 난수를 생성하는 예제입니다.
Random random = new Random();
int randomNumber = random.Next(1, 101);
Console.WriteLine($"Random number between 1 and 100: {randomNumber}");
C#
복사
문자열 처리 (String Manipulation)
설명
문자열 처리란 문자열을 다루고 조작하는 다양한 방법을 의미합니다. C#에서는 문자열을 쉽게 처리할 수 있는 다양한 메서드를 제공합니다.
문자열 생성 및 초기화
•
문자열은 큰따옴표로 묶어 생성할 수 있습니다.
string message = "Hello, World!";
C#
복사
문자열 길이 확인
•
문자열의 길이는 Length 속성을 사용하여 확인할 수 있습니다.
string message = "Hello, World!";
int length = message.Length; // 13
C#
복사
문자열 비교
•
== 연산자나 Equals 메서드를 사용하여 문자열을 비교할 수 있습니다.
string str1 = "Hello";
string str2 = "World";
bool isEqual = str1 == str2; // false
bool isEqualMethod = str1.Equals(str2); // false
C#
복사
부분 문자열 추출
•
Substring 메서드를 사용하여 문자열의 일부를 추출할 수 있습니다.
string message = "Hello, World!";
string hello = message.Substring(0, 5); // "Hello"
C#
복사
문자열 분할
•
Split 메서드를 사용하여 문자열을 특정 구분자로 나눌 수 있습니다.
string message = "Hello, World!";
string[] words = message.Split(','); // { "Hello", " World!" }
C#
복사
문자열 합치기
•
+ 연산자나 String.Concat 메서드를 사용하여 문자열을 합칠 수 있습니다.
string str1 = "Hello";
string str2 = "World";
string message = str1 + ", " + str2 + "!"; // "Hello, World!"
C#
복사
문자열 포맷팅
•
String.Format 메서드를 사용하여 문자열을 포맷팅할 수 있습니다.
string name = "John";
int age = 30;
string message = String.Format("Name: {0}, Age: {1}", name, age); // "Name: John, Age: 30"
C#
복사
문자 배열 변환
•
문자열을 문자 배열로 변환하거나, 그 반대 작업을 할 수 있습니다.
string message = "Hello";
char[] chars = message.ToCharArray(); // { 'H', 'e', 'l', 'l', 'o' }
string newMessage = new string(chars); // "Hello"
C#
복사
out과 ref (Pass by Reference)
설명
C#에서 out과 ref 키워드는 메서드에 인수로 전달된 변수를 참조로 전달하는 데 사용됩니다. 둘 다 메서드 내부에서 값을 변경할 수 있으며, 메서드 호출 후에도 변경된 값이 반영됩니다.
out
•
사용 예: 메서드가 여러 값을 반환해야 할 때 유용합니다.
•
특징:
◦
메서드가 반환하기 전에 반드시 값을 할당해야 합니다.
◦
호출할 때 초기화되지 않아도 됩니다.
예제 코드:
void GetValues(out int x, out int y)
{
x = 10;
y = 20;
}
int a, b;
GetValues(out a, out b);
Console.WriteLine($"a: {a}, b: {b}"); // a: 10, b: 20
C#
복사
ref
•
사용 예: 변수의 현재 값을 메서드 내부에서 수정해야 할 때 유용합니다.
•
특징:
◦
메서드가 호출될 때 변수는 초기화되어 있어야 합니다.
◦
메서드 내부에서 값을 수정할 수 있습니다.
예제 코드:
void Increment(ref int number)
{
number++;
}
int value = 5;
Increment(ref value);
Console.WriteLine(value); // 6
C#
복사
차이점:
•
out은 메서드 내부에서 값을 할당해야 하며, 초기화되지 않은 변수를 받을 수 있습니다.
•
ref는 변수의 초기화가 필요하며, 메서드 호출 전에 이미 할당된 값을 전달받습니다.
is와 as (Type Checking and Casting)
설명
C#에서 is와 as 키워드는 객체의 타입을 확인하고 변환하는 데 사용됩니다. 두 키워드는 타입 검사 및 변환을 더 간단하고 안전하게 수행할 수 있도록 도와줍니다.
is (타입 확인)
•
사용 예: 객체가 특정 타입인지 확인할 때 사용합니다.
•
특징:
◦
결과는 true 또는 false로 반환됩니다.
◦
타입이 일치하면 true, 그렇지 않으면 false를 반환합니다.
예제 코드:
object obj = "Hello, World!";
if (obj is string)
{
Console.WriteLine("obj is a string");
}
else
{
Console.WriteLine("obj is not a string");
}
C#
복사
as (타입 변환)
•
사용 예: 객체를 특정 타입으로 안전하게 변환할 때 사용합니다.
•
특징:
◦
타입 변환이 성공하면 변환된 객체를 반환합니다.
◦
실패하면 null을 반환합니다.
예제 코드:
object obj = "Hello, World!";
string str = obj as string;
if (str != null)
{
Console.WriteLine("Conversion successful: " + str);
}
else
{
Console.WriteLine("Conversion failed");
}
C#
복사
차이점:
•
is는 객체가 특정 타입인지 확인하는 데 사용됩니다.
•
as는 객체를 특정 타입으로 변환하는 데 사용되며, 변환에 실패하면 null을 반환합니다.