전자책 위주로 출간하고 있으며, 현재도 새로운 책을 준비 중입니다.

a=10
a=10
b=20
c=a+b
print(c)
print('안녕')
print("안녕, friend")
a=10
print(a)
a=10
print('a')
a=10
b='사탕'
print(f"나는 어제 {a}개의 {b}을 먹었다.")
a=10
b='사탕'
print(f"나는 어제 a개의 b을 먹었다.")
a=10
b=-20
c=0
d=0.2
e=-3.0
a=10
b=-20
c=0
d=0.2
e=-3.0
f=a+b
g=a*e
h=a-d
print(f, g, h)
print(f"{f} , {g} , {h}")
a=7
b=3
f=a/b
g=a//b
h=a%b
print(f, g, h)
print(f"{f} / {g} / {h}")
a=100
b='100'
c=a
d='a'
a='hello'
b='hi'
print(a)
print(a+b)
print(a*3)
a='2021'
a='2021'
b=int(a)
a='hi python'
a='hi python'
b=a[0]
c=a[3]
print(b)
print(c)
a='hi python'
b=a[3]
c=a[3:7]
d=a[1:7:2]
print(b)
print(c)
print(d)
a=[1,4,8,9,13]
b=['I', 'love', 'python']
c=['candy',1,'buy',6,['love',7],'apple']
a=[1,4,8,9,13]
b=['I', 'love', 'python']
c=['candy',1,'buy',6,['love',7],'apple']
print(a[3])
print(a[2:4])
print(b[0])
print(c[4][0])
a={'school':'daehan','grade':2,'birth':1219}
a={'school':'daehan','grade':2,'birth':1219}
print(a['school'])
print(a['grade'])
a={'school':'daehan','grade':2,'birth':1219}
a['grade']=200
a['year']=2021
print(a)
a={'school':'daehan','grade':2,'birth':1219}
x=a.keys()
y=a.values()
z=a.items()
print(list(x))
print(list(y))
print(list(z))
money=1000
candy=200
if money>candy:
print('캔디를 살 수 있다.')
else:
print('캔디를 살 수 없다.')
money=1000
candy=200
if money<candy:
print('캔디를 살 수 있다.')
else:
print('캔디를 살 수 없다.')
money=1000
candy=200
if money<candy:
print('캔디를 살 수 있다.')
money=1000
candy=200
point=10
if money<candy or point>7:
print('캔디를 살 수 있다.')
else:
print('캔디를 살 수 없다.')
money=5
candy=7
point=2
if money>candy:
print('1-캔디를 살 수 있다.')
elif money==candy:
print('2-캔디를 살 수 있다.')
elif point>=2:
print('3-캔디를 살 수 있다.')
else:
print('캔디를 살 수 없다.')
a=['apple', 2021, 'Z', 10, 90, 'yellow']
if 'Z' in a:
print('Z가 들어 있으므로 실행된다.')
a=int(input('정수 하나를 입력하시오: '))
b=int(input('정수 하나를 입력하시오: '))
c=int(input('정수 하나를 입력하시오: '))
if a>b and a>c:
print("가장 큰 수는 a ")
elif b>a and b>c:
print("가장 큰 수는 b ")
else:
print("가장 큰 수는 c ")
a=int(input('정수 하나를 입력하시오: '))
b=int(input('정수 하나를 입력하시오: '))
c=int(input('정수 하나를 입력하시오: '))
if a>b:
if a>c:
print("가장 큰 수는 a ")
else:
print("가장 큰 수는 c ")
else:
if b>c:
print("가장 큰 수는 b ")
else:
print("가장 큰 수는 c ")
clear = 0
while clear < 5 :
print(f'현재까지 게임을 {clear}번 클리어 했습니다. ')
clear = clear +1
if clear == 5:
print('레벨이 올라갑니다.')
cupramen = 4
while True :
money = int(input('돈을 넣으세요'))
if money == 1500:
print('컵라면을 줍니다')
cupramen = cupramen -1
elif money > 1500:
print(f'컵라면을 주고, 거스름돈 {money-1500}원을 돌려 줍니다')
cupramen = cupramen -1
else :
print('돈이 모자랍니다. 돈을 돌려줍니다')
if cupramen == 0:
print('컵라면이 다 떨어졌습니다. ')
break
people=int(input('학생수를 입력하시오: '))
count=1
sum=0
while count<=people:
num = int(input(f"{count}번 학생의 점수를 입력하세요: "))
sum+=num
count+=1
print(f"총합계는 {sum}입니다.")
print(f"평균은 {sum/people}입니다.")
a=[34,67,43,89,55,3,45]
z=a[0]
b=0
while b<len(a):
if z>a[b]:
z=a[b]
b+=1
print(z)
a=[[1,2],[3,4,300,400],[5,6]]
print(a)
print(a[1])
print(a[1][2])
a=[[1,2],[3,4,300,400],[5,6]]
b=0
while b<len(a):
print(a[b])
b+=1
a=[[1,2],[3,4,300,400],[5,6]]
b=0
while b<len(a):
c=0
while c<len(a[b]):
print(a[b][c], end=' ')
c+=1
b+=1
a=[34,67,43,89,55,3,45]
i=0
while i <(len(a)):
j=i
while j <len(a):
if a[i]>a[j]:
b=a[i]
a[i]=a[j]
a[j]=b
j+=1
i+=1
print(a)
list = ['a', 'b', 'c']
for z in list:
print(z, end=' ')
list = ['a', 'b', 'c']
for z in list:
print('k', end=' ')
a=[12,13,14,15,16,17]
for b in a:
if b%2==0:
print(b, end=' ')
a=[12,13,14,15,16,17]
for b in range(len(a)):
if a[b]%2==0:
print(a[b], end=' ')
num=int(input())
sum=0
for a in range(1,num+1):
sum+=a
print(sum)
a=[[1,2],[3,4,300,400],[5,6]]
for b in range(len(a)):
for c in range(len(a[b])):
print(a[b][c], end=' ')
a=[34,67,43,89,55,3,45]
z=a[0]
for b in a:
if z<b:
z=b
print(z)
a=[34,67,43,89,55,3,45]
z=a[0]
for b in range(len(a)):
if z<a[b]:
z=a[b]
print(z)
a=[34,67,43,89,55,3,45]
for b in range(len(a)):
for c in range(b,len(a)):
if a[b]>a[c]:
e=a[b]
a[b]=a[c]
a[c]=e
print(a)
# 어떤 게임 유저가 아래와 같이 아이템과 게임 머니를 가지고 있다.
item=0
money=100
z = input("A 아이템을 사겠다면 yes 를 입력. 한 개에 10골드 ")
# 아이템을 하나 구매한다.
if z == "yes":
item += 1
money -= 10
print("나의 아이템은 ",item,"개", "골드는 ",money,"있다")
def item_buy(item,money):
z = input("A 아이템을 사겠다면 yes 를 입력. 한 개에 10골드 ")
if z == "yes":
item += 1
money -= 10
print("나의 아이템은 ",item,"개", "골드는 ",money,"있다")
def item_buy(item,money):
z = input("A 아이템을 사겠다면 yes 를 입력. 한 개에 10골드 ")
if z == "yes":
item += 1
money -= 10
print("나의 아이템은 ",item,"개", "골드는 ",money,"있다")
item=0
money=100
item_buy(item, money)
def num():
a=10
b=20
print(a+b)
num()
def num():
a=10
b=20
return a+b
c=num()
print(c)
def num(j, k ):
print(j+k)
x=40
y=50
num(x, y)
def num(j, k ):
return j+k
x=40
y=50
c=num(x, y)
print(c)
def add(a , b):
return a+b, a*b, a-b
print(add(4,6))
def add(a,b):
return a +b
return a*b
print(add(4,6))
def add(x , y):
z=x+y
return z
def mul(a,b):
c=a*b
d=a+b
e=add(c,d)
f=e/2
return f
ans=mul(2, 3)
print(ans)
def people_number(max, people):
answer = 0
total = 0
for i in range(len(people)):
total += people[i]
if total > max:
break
answer += 1
return answer
max_weight = 300 #300kg
people_weights = [65, 77, 80, 45, 90, 110, 72, 88, 41, 99]
response = people_number(max_weight,people_weights)
print(response)
def max_point(scores):
answer = scores[0]
for sc in scores:
if answer<sc:
answer = sc
return answer
def min_point(scores):
answer = scores[0]
for sc in scores:
if answer > sc:
answer = sc
return answer
def dif_point(max, min):
return max-min
def final_point(scores):
max=max_point(scores)
min=min_point(scores)
answer=dif_point(max,min)
return answer
points=[9.5, 8.8, 7.0, 7.9, 10]
response=final_point(points)
print(response)
def a():
print('hi')
a()
a()
def count(a):
if a==0:
return
print(a, end=' ')
a-=1
count(a)
k=5
count(k)
def count(a):
if a==0:
return
a-=1
count(a)
print(a, end=' ')
k=5
count(k)
def sum(a):
if a == 0:
return 0
return a+sum(a-1)
k=int(input("정수 하나를 입력하시오: "))
print(sum(k))
def multi(a):
if a == 1:
return 1
return a*multi(a-1)
k=int(input("정수 하나를 입력하시오: "))
print(multi(k))
class Game:
name="king"
weapon="thunder"
hp=999
class Game:
name="king"
weapon="thunder"
hp=999
kim=Game()
print(kim.name, end=" ")
print(kim.weapon,end=" ")
print(kim.hp,end=" ")
class Game:
name="king"
weapon="thunder"
hp=999
kim=Game()
print(kim.name, end=" ")
print(kim.weapon,end=" ")
print(kim.hp,end=" ")
print()
park=Game()
print(park.name, end=" ")
print(park.weapon,end=" ")
print(park.hp,end=" ")
class Game:
def meet(self):
print('hi')
class Game:
def meet(self):
print('hi')
a=Game()
a.meet()
b=Game()
b.meet()
class Game:
korea='안녕'
def meet(self):
print(self.korea)
a=Game()
a.meet()
b=Game()
b.meet()
class Game:
korea='안녕'
def meet(self):
print(korea)
a=Game()
a.meet()
b=Game()
b.meet()
class Calculator:
def data(self, one, two):
self.one=one
self.two=two
def plus(self):
result=self.one+self.two
return result
def minus(self):
result=self.one-self.two
return result
def mulipl(self):
result = self.one * self.two
return result
def division(self):
result = self.one / self.two
return result
a=Calculator()
a.data(10,20)
print(a.plus())
print(a.minus())
print(a.mulipl())
print(a.division())
class Calculator:
def __init__(self, one, two):
self.one=one
self.two=two
def plus(self):
result=self.one+self.two
return result
def minus(self):
result=self.one-self.two
return result
def mulipl(self):
result = self.one * self.two
return result
def division(self):
result = self.one / self.two
return result
a=Calculator(10,20)
print(a.plus())
print(a.minus())
print(a.mulipl())
print(a.division())
class Point:
def __init__(self, score):
self.list_score=score
def final_point(self):
total=sum(self.list_score)-max(self.list_score)-min(self.list_score)
result=total/(len(self.list_score)-2)
return result
swimming=Point(list(map(int,input().split())))
print(swimming.final_point( ))
class Game:
def user(self):
print("게임을 시작합니다")
class Player(Game):
def person1(self):
print("캐릭터를 고르세요")
user1=Player()
user1.user()
user1.person1()
class Game:
def __init__(self):
print("게임을 시작합니다")
self.hi="안녕!"
class Player(Game):
def __init__(self):
print("캐릭터를 고르세요")
super().__init__()
self.name="신호등"
user1=Player()
print(user1.name)
print(user1.hi)
class Game_name:
def hi(self):
print("안녕")
class User(Game_name):
def hi(self):
print("hi, how are you?")
one=User()
one.hi()
class Game_name:
def hi(self):
print("안녕")
class User(Game_name):
def hi(self):
print("hi, how are you?")
def hi2(self):
super().hi()
one=User()
one.hi()
one.hi2()

#include <stdio.h>
int main() {
//여기서 코드들을 작성합니다.
return 0;
}
#include <stdio.h>
int main() {
int a;
a = 10;
return 0;
}
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
int c = a + b;
printf("%d\n", c);
return 0;
}
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
int c = a + b;
printf("%d\n", c);
return 0;
}
#include <stdio.h>
int main() {
printf("안녕\n");
printf("안녕, friend\n");
return 0;
}
#include <stdio.h>
int main() {
int a = 10;
printf("%d\n", a);
return 0;
}
#include <stdio.h>
int main() {
int a = 10;
printf("나는 어제 %d개의 사탕을 먹었습니다.\n", a);
return 0;
}
int a = 10; // 정수
int b = -20; // 음수
int c = 0; // 0
float d = 0.2; // 실수
double f = 3.14159; // 더 정밀한 실수
#include <stdio.h>
int main() {
int a = 10;
int b = -20;
float d = 0.2;
float e = -3.0;
int f = a + b;
float g = a * e;
float h = a - d;
printf("%d, %f, %f\n", f, g, h);
return 0;
}
#include <stdio.h>
int main() {
int a = 7;
int b = 3;
int f = a / b; // 몫
int g = a % b; // 나머지
float h = (float)a / b; // 실수 나눗셈
printf("%d, %d, %f\n", f, g, h);
return 0;
}
#include <stdio.h>
int main() {
int money = 5000;
int apple = 800;
int count = money / apple;
printf("사과를 %d개 살 수 있습니다.\n", count);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int a, b;
printf("첫 번째 정수를 입력하세요: ");
scanf("%d", &a);
printf("두 번째 정수를 입력하세요: ");
scanf("%d", &b);
printf("합: %d\n", a + b);
printf("차: %d\n", a - b);
printf("곱: %d\n", a * b);
printf("몫: %d\n", a / b);
printf("나머지: %d\n", a % b);
return 0;
}
#include <stdio.h>
int main() {
char a = 'A';
printf("%c\n", a);
return 0;
}
#include <stdio.h>
int main() {
char ch1 = 'A';
char ch2 = 'B';
char ch3 = 'C';
printf("문자: %c, %c, %c\n", ch1, ch2, ch3);
printf("문자의 ASCII 값: %d, %d, %d\n", ch1, ch2, ch3);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char name;
int age;
printf("이름의 이니셜을 입력하시오: ");
scanf("%c", &name);
printf("나이를 입력하세요: ");
scanf("%d", &age);
printf("안녕하세요, %c님! 당신은 %d살입니다.\n", name, age);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char ch;
printf("문자를 입력하세요: ");
scanf(" %c", &ch);
printf("입력한 문자: %c\n", ch);
printf("ASCII 값: %d\n", ch);
printf("다음 문자: %c\n", ch + 1);
return 0;
}
#include <stdio.h>
int main() {
int money = 1000;
int candy = 200;
if (money > candy) {
printf("캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
return 0;
}
#include <stdio.h>
int main() {
int money = 1000;
int candy = 200;
int point = 10;
if (money < candy || point > 7) {
printf("캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
return 0;
}
#include <stdio.h>
int main() {
int money = 5;
int candy = 7;
int point = 2;
if (money > candy) {
printf("1-캔디를 살 수 있습니다.\n");
} else if (money == candy) {
printf("2-캔디를 살 수 있습니다.\n");
} else if (point >= 2) {
printf("3-캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int age;
printf("나이를 입력하세요: ");
scanf("%d", &age);
if (age >= 20)
printf("성인\n");
else
printf("미성년자\n");
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int a, b, c;
printf("정수 세 개를 입력하세요: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c)
printf("가장 큰 수는 %d입니다.\n", a);
else if (b > a && b > c)
printf("가장 큰 수는 %d입니다.\n", b);
else
printf("가장 큰 수는 %d입니다.\n", c);
return 0;
}
#include <stdio.h>
int main() {
int score = 3;
switch (score) {
case 1:
printf("C등급입니다.\n");
break;
case 2:
printf("B등급입니다.\n");
break;
case 3:
printf("A등급입니다.\n");
break;
default:
printf("등급을 매길 수 없습니다.\n");
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int menu;
printf("메뉴를 선택하세요 (1-3): ");
scanf("%d", &menu);
switch (menu) {
case 1:
printf("햄버거를 선택하셨습니다.\n");
break;
case 2:
printf("피자를 선택하셨습니다.\n");
break;
case 3:
printf("치킨을 선택하셨습니다.\n");
break;
default:
printf("잘못된 선택입니다.\n");
}
return 0;
}
#include <stdio.h>
int main() {
int clear = 0;
while (clear < 5) {
printf("현재까지 게임을 %d번 클리어 했습니다.\n", clear);
clear = clear + 1;
if (clear == 5) {
printf("레벨이 올라갑니다.\n");
}
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int cupramen = 4;
while (1) {
int money;
printf("돈을 넣으세요: ");
scanf("%d", &money);
if (money == 1500) {
printf("컵라면을 줍니다\n");
cupramen = cupramen - 1;
} else if (money > 1500) {
printf("컵라면을 주고, 거스름돈 %d원을 돌려 줍니다\n", money - 1500);
cupramen = cupramen - 1;
} else {
printf("돈이 모자랍니다. 돈을 돌려줍니다\n");
}
if (cupramen == 0) {
printf("컵라면이 다 떨어졌습니다.\n");
break;
}
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int num, sum = 0;
while (1) {
printf("숫자를 입력하세요 (0 입력 시 종료): ");
scanf("%d", &num);
if (num == 0) break;
sum += num;
}
printf("총합: %d\n", sum);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int people, count = 1, sum = 0, num;
printf("학생수를 입력하시오: ");
scanf("%d", &people);
while (count <= people) {
printf("%d번 학생의 점수를 입력하세요: ", count);
scanf("%d", &num);
sum += num;
count++;
}
printf("총합계는 %d입니다.\n", sum);
printf("평균은 %.2f입니다.\n", (float)sum / people);
return 0;
}
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int num, sum = 0;
printf("정수를 입력하세요: ");
scanf("%d", &num);
for (int i = 1; i <= num; i++) {
sum += i;
}
printf("합: %d\n", sum);
return 0;
}
#include <stdio.h>
int main() {
int i = 0;
while (i < 3) {
int j = 0;
while (j < 4) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}
return 0;
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= i) {
printf("*");
j++;
}
printf("\n");
i++;
}
return 0;
}
#include <stdio.h>
int main() {
int dan = 2;
while (dan <= 5) {
int num = 1;
printf("=== %d단 ===\n", dan);
while (num <= 9) {
printf("%d × %d = %d\n", dan, num, dan * num);
num++;
}
printf("\n");
dan++;
}
return 0;
}
#include <stdio.h>
int main() {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
// 공백 출력
for (j = 1; j <= 5 - i; j++) {
printf(" ");
}
// 숫자 출력
for (k = 1; k <= 2 * i - 1; k++) {
printf("%d", k);
}
printf("\n");
}
return 0;
}
// 배열을 사용하지 않을 때
int score1 = 85;
int score2 = 90;
int score3 = 78;
int score4 = 92;
int score5 = 88;
// 배열을 사용할 때
int score[5] = {85, 90, 78, 92, 88};
// 방법 1: 크기만 지정
int arr[5];
// 방법 2: 크기와 함께 초기화
int arr[5] = {1, 2, 3, 4, 5};
// 방법 3: 크기를 생략하고 초기화
int arr[] = {1, 2, 3, 4, 5};
// 방법 4: 일부만 초기화 (나머지는 0으로 초기화)
int arr[5] = {1, 2}; // {1, 2, 0, 0, 0}
#include <stdio.h>
int main() {
int arr1[5] = {10, 20, 30, 40, 50};
int arr2[5] = {10, 20}; // 나머지는 0
int arr3[] = {1, 2, 3}; // 크기는 3
printf("arr1[0] = %d\n", arr1[0]);
printf("arr2[4] = %d\n", arr2[4]); // 0이 출력됨
printf("arr3의 크기: 자동으로 3\n");
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("배열이 초기화되었습니다.\n");
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
printf("arr[0] = %d\n", arr[0]); // 첫 번째 요소
printf("arr[1] = %d\n", arr[1]); // 두 번째 요소
printf("arr[4] = %d\n", arr[4]); // 마지막 요소
// 배열 요소 값 변경
arr[2] = 100;
printf("변경 후 arr[2] = %d\n", arr[2]);
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {1, 4, 8, 9, 13};
int i;
// 배열의 모든 요소 출력
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {34, 67, 43, 89, 55, 3, 45};
int max = arr[0];
int i;
for (i = 1; i < 7; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
printf("가장 큰 수는 %d입니다.\n", max);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int sum = 0;
int i;
float average;
for (i = 0; i < 5; i++) {
sum += arr[i];
}
average = (float)sum / 5;
printf("합: %d\n", sum);
printf("평균: %.2f\n", average);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {34, 67, 43, 89, 55, 3, 45};
int min = arr[0];
int i = 1;
while (i < 7) {
if (min > arr[i]) {
min = arr[i];
}
i++;
}
printf("가장 작은 수는 %d입니다.\n", min);
return 0;
}
#include <stdio.h>
int main() {
// 2차원 배열 선언: 3행 4열
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("%d\n", arr[0][0]); // 첫 번째 행, 첫 번째 열
printf("%d\n", arr[1][2]); // 두 번째 행, 세 번째 열
printf("%d\n", arr[2][3]); // 세 번째 행, 네 번째 열
return 0;
}
#include <stdio.h>
int main() {
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int i, j;
// 2차원 배열 출력
for (i = 0; i < 3; i++) { // 행
for (j = 0; j < 4; j++) { // 열
printf("%d ", arr[i][j]);
}
printf("\n"); // 한 행이 끝나면 줄바꿈
}
return 0;
}
#include <stdio.h>
int main() {
int scores[3][4] = {
{85, 90, 78, 92},
{88, 76, 95, 87},
{92, 85, 90, 88}
};
int i, j, sum;
float average;
for (i = 0; i < 3; i++) {
sum = 0;
for (j = 0; j < 4; j++) {
sum += scores[i][j];
}
average = (float)sum / 4;
printf("%d번 학생의 평균: %.2f\n", i + 1, average);
}
return 0;
}
// 문자 한 개
char ch = 'A';
// 문자열
char str[] = "Hello"; // 실제로는 {'H', 'e', 'l', 'l', 'o', '\0'}
// 방법 1: 크기 지정 없이 초기화
char str1[] = "Hello";
// 방법 2: 크기를 지정하고 초기화
char str2[10] = "Hello";
// 방법 3: 크기만 지정 (나중에 값 할당)
char str3[20];
// 방법 4: 문자 배열로 초기화
char str4[] = {'H', 'e', 'l', 'l', 'o', '\0'};
#include <stdio.h>
int main() {
char str1[] = "Hello";
char str2[10] = "World";
char str3[20] = "C Programming";
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
printf("str3: %s\n", str3);
return 0;
}
#include <stdio.h>
int main() {
char name[20] = "홍길동";
printf("이름: %s\n", name);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char name[20];
printf("이름을 입력하세요: ");
scanf("%s", name); // & 기호 없이 사용
printf("안녕하세요, %s님!\n", name);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char name[20];
int age;
printf("이름을 입력하세요: ");
scanf("%s", name);
printf("나이를 입력하세요: ");
scanf("%d", &age);
printf("안녕하세요, %s님! 당신은 %d살입니다.\n", name, age);
return 0;
}
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
// strlen(): 문자열 길이
printf("str1의 길이: %d\n", (int)strlen(str1));
// strcpy(): 문자열 복사
char str3[20];
strcpy(str3, str1);
printf("복사된 문자열: %s\n", str3);
// strcat(): 문자열 연결
strcat(str1, str2);
printf("연결된 문자열: %s\n", str1);
// strcmp(): 문자열 비교
if (strcmp(str2, "World") == 0) {
printf("문자열이 같습니다.\n");
}
return 0;
}
#include <stdio.h>
int main() {
char str[] = "Hello";
int i;
// for 반복문으로 문자 하나씩 출력
for (i = 0; str[i] != '\0'; i++) {
printf("%c ", str[i]);
}
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
char str[] = "Hello World";
int i, count = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
count++;
}
}
printf("대문자 개수: %d\n", count);
return 0;
}
#include <stdio.h>
int main() {
char str[] = "Hello World";
char target = 'l';
int i, count = 0;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == target) {
count++;
}
}
printf("'%c' 문자가 %d번 나타납니다.\n", target, count);
return 0;
}
#include <stdio.h>
int main() {
char names[3][20] = {"홍길동", "김철수", "이영희"};
int i;
// 모든 이름 출력
for (i = 0; i < 3; i++) {
printf("%d번: %s\n", i + 1, names[i]);
}
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char names[3][20];
int i;
printf("3명의 이름을 입력하세요:\n");
for (i = 0; i < 3; i++) {
printf("%d번: ", i + 1);
scanf("%s", names[i]);
}
printf("\n입력한 이름:\n");
for (i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}
return 0;
}
int a = 10; // 변수 a에 10 저장
int *ptr = &a; // 포인터 ptr에 변수 a의 주소 저장
// 의미:
// a → 값 (10)
// &a → 주소 (변수 a의 메모리 주소)
// ptr → 주소를 저장
// *ptr → 그 주소에 들어 있는 값 (10)
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a; // 포인터 선언 및 초기화
printf("a의 값: %d\n", a);
printf("a의 주소: %p\n", &a);
printf("ptr이 저장한 주소: %p\n", ptr);
printf("ptr이 가리키는 값: %d\n", *ptr);
return 0;
}
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
printf("초기값: a = %d\n", a);
// 포인터를 통해 값 변경
*ptr = 20;
printf("변경 후: a = %d\n", a);
// 포인터를 통해 값 읽기
printf("포인터로 읽은 값: %d\n", *ptr);
return 0;
}
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 3, y = 7;
printf("교환 전: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("교환 후: x = %d, y = %d\n", x, y);
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // 배열 이름은 첫 번째 요소의 주소
printf("ptr이 가리키는 값: %d\n", *ptr); // 10
printf("ptr+1이 가리키는 값: %d\n", *(ptr+1)); // 20
printf("ptr+2가 가리키는 값: %d\n", *(ptr+2)); // 30
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // 배열 이름은 주소
printf("arr[0] = %d\n", arr[0]);
printf("*arr = %d\n", *arr);
printf("*ptr = %d\n", *ptr);
printf("\narr[2] = %d\n", arr[2]);
printf("*(arr + 2) = %d\n", *(arr + 2));
printf("*(ptr + 2) = %d\n", *(ptr + 2));
return 0;
}
#include <stdio.h>
int sum(int *p, int size) {
int total = 0;
int i;
for (i = 0; i < size; i++) {
total += *(p + i);
}
return total;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("합: %d\n", sum(arr, 5));
return 0;
}
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
int i;
// 방법 1: 포인터에 인덱스 사용
printf("방법 1: ");
for (i = 0; i < 5; i++) {
printf("%d ", ptr[i]); // 포인터도 배열처럼 사용 가능
}
printf("\n");
// 방법 2: 포인터 연산
printf("방법 2: ");
for (i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
// 방법 3: 포인터 증가
printf("방법 3: ");
ptr = arr; // 다시 처음으로
for (i = 0; i < 5; i++) {
printf("%d ", *ptr);
ptr++;
}
printf("\n");
return 0;
}
#include <stdio.h>
int findMax(int *arr, int size) {
int max = *arr; // 첫 번째 요소
int i;
for (i = 1; i < size; i++) {
if (max < *(arr + i)) {
max = *(arr + i);
}
}
return max;
}
int main() {
int arr[] = {34, 67, 43, 89, 55, 3, 45};
printf("최댓값: %d\n", findMax(arr, 7));
return 0;
}
#include <stdio.h>
int main() {
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int i, j;
// 2차원 배열을 포인터로 접근
int *ptr = &arr[0][0]; // 첫 번째 요소의 주소
for (i = 0; i < 12; i++) {
printf("%d ", *(ptr + i));
if ((i + 1) % 4 == 0) {
printf("\n");
}
}
return 0;
}
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *ptr_arr[3]; // 포인터 배열
ptr_arr[0] = &a;
ptr_arr[1] = &b;
ptr_arr[2] = &c;
int i;
for (i = 0; i < 3; i++) {
printf("ptr_arr[%d]가 가리키는 값: %d\n", i, *ptr_arr[i]);
}
return 0;
}
#include <stdio.h>
int main() {
char *names[3] = {"홍길동", "김철수", "이영희"};
int i;
for (i = 0; i < 3; i++) {
printf("%d번: %s\n", i + 1, names[i]);
}
return 0;
}
#include <stdio.h>
// 함수 정의
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20); // 함수 호출
printf("%d\n", result);
return 0;
}
#include <stdio.h>
// 형태 1: 매개변수 없고, 리턴 값 없음
void printHello() {
printf("Hello!\n");
}
// 형태 2: 매개변수 없고, 리턴 값 있음
int getNumber() {
return 100;
}
// 형태 3: 매개변수 있고, 리턴 값 없음
void printSum(int a, int b) {
printf("%d\n", a + b);
}
// 형태 4: 매개변수 있고, 리턴 값 있음
int add(int a, int b) {
return a + b;
}
int main() {
printHello();
int num = getNumber();
printf("%d\n", num);
printSum(40, 50);
int result = add(40, 50);
printf("%d\n", result);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int isEven(int num) {
if (num % 2 == 0)
return 1;
else
return 0;
}
int main() {
int num;
printf("정수를 입력하세요: ");
scanf("%d", &num);
if (isEven(num))
printf("짝수입니다.\n");
else
printf("홀수입니다.\n");
return 0;
}
#include <stdio.h>
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
return 0;
}
#include <stdio.h>
void doubleArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
arr[i] = arr[i] * 2; // 원본 배열 수정
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
printf("원본: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
doubleArray(arr, 5);
printf("변경 후: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
#include <stdio.h>
int sumArray(int arr[], int size) {
int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int total = sumArray(arr, 5);
printf("합: %d\n", total);
return 0;
}
#include <stdio.h>
void print2DArray(int arr[][4], int rows) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
print2DArray(arr, 3);
return 0;
}
#include <stdio.h>
// 값으로 전달 (원본 변경 안 됨)
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// 포인터로 전달 (원본 변경 됨)
void swapByPointer(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("원본: x = %d, y = %d\n", x, y);
swapByValue(x, y);
printf("값으로 전달 후: x = %d, y = %d\n", x, y);
swapByPointer(&x, &y);
printf("포인터로 전달 후: x = %d, y = %d\n", x, y);
return 0;
}
#include <stdio.h>
// 방법 1: 배열 표기법
int sum1(int arr[], int size) {
int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
// 방법 2: 포인터 표기법
int sum2(int *arr, int size) {
int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += *(arr + i);
}
return sum;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
printf("방법 1: %d\n", sum1(arr, 5));
printf("방법 2: %d\n", sum2(arr, 5));
return 0;
}
#include <stdio.h>
void count(int a) {
if (a == 0) {
return; // 종료 조건
}
printf("%d ", a);
count(a - 1); // 자기 자신 호출
}
int main() {
count(5);
return 0;
}
#include <stdio.h>
void count(int a) {
if (a == 0) {
return;
}
count(a - 1); // 먼저 재귀 호출
printf("%d ", a); // 나중에 출력
}
int main() {
count(5);
return 0;
}
#include <stdio.h>
int sum(int n) {
if (n == 0) {
return 0; // 종료 조건
}
return n + sum(n - 1); // n + (n-1까지의 합)
}
int main() {
int result = sum(10);
printf("1부터 10까지의 합: %d\n", result);
return 0;
}
// 구조체를 사용하지 않을 때
char name[20];
int age;
int score;
// 구조체를 사용할 때
struct Student {
char name[20];
int age;
int score;
};
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
int score;
};
int main() {
struct Student s1;
strcpy(s1.name, "홍길동");
s1.age = 20;
s1.score = 95;
printf("이름: %s, 나이: %d, 점수: %d\n", s1.name, s1.age, s1.score);
return 0;
}
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
int main() {
struct Student students[3] = {
{"김철수", 85},
{"이영희", 92},
{"박민수", 78}
};
int i;
for (i = 0; i < 3; i++) {
printf("%s: %d점\n", students[i].name, students[i].score);
}
return 0;
}
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
void printStudent(struct Student s) {
printf("이름: %s, 점수: %d\n", s.name, s.score);
}
int main() {
struct Student s1 = {"홍길동", 95};
printStudent(s1);
return 0;
}
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Point addPoints(struct Point p1, struct Point p2) {
struct Point result;
result.x = p1.x + p2.x;
result.y = p1.y + p2.y;
return result;
}
int main() {
struct Point p1 = {10, 20};
struct Point p2 = {30, 40};
struct Point sum = addPoints(p1, p2);
printf("합: (%d, %d)\n", sum.x, sum.y);
return 0;
}

print('hello') # 여기에 코드를 작성한다
#include <stdio.h>
int main() {
// 여기에 코드를 작성한다
return 0;
}
print('hello')
#include <stdio.h>
int main() {
printf("hello\n");
return 0;
}
a = 10
int a = 10;
a = 10
b = 20
c = a + b
int a = 10;
int b = 20;
int c = a + b;
print('안녕')
print("안녕, friend")
printf("안녕\n");
printf("안녕, friend\n");
a = 10
print(a)
int a = 10;
printf("%d\n", a);
a = 10
b = '사탕'
print(f"나는 어제 {a}개의 {b}을 먹었습니다.")
int a = 10;
printf("나는 어제 %d개의 ", a);
printf("사탕을 먹었습니다.\n");
a = 10
b = -20
c = 0
d = 0.2
e = -3.0
int a = 10; // 정수
int b = -20; // 음수
int c = 0; // 0
float d = 0.2; // 실수
double e = -3.0; // 더 정밀한 실수
a = 10
e = -3.0
d = 0.2
f = a + (-20)
g = a * e
h = a - d
print(f"{f} , {g} , {h}")
int a = 10;
float e = -3.0;
float d = 0.2;
int f = a + (-20);
float g = a * e;
float h = a - d;
printf("%d , %f , %f\n",
f, g, h);
a = 7
b = 3
print(a / b) # 나누기
print(a // b) # 몫
print(a % b) # 나머지
int a = 7;
int b = 3;
printf("%d\n", a / b);
printf("%d\n", a % b);
printf("%f\n", (float)a / b);
money = 5000
apple = 800
count = money // apple
print(f"사과를 {count}개 살 수 있습니다.")
int money = 5000;
int apple = 800;
int count = money / apple;
printf("사과를 %d개 살 수 있습니다.\n",
count);
a = 'A'
print(a)
char a = 'A';
printf("%c\n", a);
char ch1 = 'A';
char ch2 = 'B';
printf("문자: %c, %c\n", ch1, ch2);
printf("ASCII: %d, %d\n", ch1, ch2);
a = 'hello'
b = 'hi'
print(a + b)
print(a * 3)
a = 'hi python'
print(a[3]) # 한 글자
print(a[3:7]) # 3번부터 6번까지
print(a[1:7:2]) # 두 칸씩
a = [1, 4, 8, 9, 13]
b = ['I', 'love', 'python']
c = ['candy', 1, 'buy', 6,
['love', 7], 'apple']
print(a[3]) # 인덱스 3번
print(a[2:4]) # 2번부터 3번까지
print(c[4][0]) # 리스트 속 리스트
a = {'school': 'daehan',
'grade': 2,
'birth': 1219}
print(a['school']) # 키로 값 찾기
a['grade'] = 200 # 기존 키 수정
a['year'] = 2021 # 새 키 추가
print(a)
money = 1000
candy = 200
if money > candy:
print('캔디를 살 수 있습니다.')
else:
print('캔디를 살 수 없습니다.')
int money = 1000;
int candy = 200;
if (money > candy) {
printf("캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
x < y # x가 y보다 작음
x > y # x가 y보다 큼
x >= y # x가 y보다 크거나 같음
x <= y # x가 y보다 작거나 같음
x == y # x와 y가 같음
x != y # x와 y가 다름
# or / and / not
x or y # 둘 중 하나만 참이어도 참
x and y # 둘 다 참이어야 참
not x # x가 거짓이면 참
// || / && / !
x || y // 둘 중 하나만 참이어도 참
x && y // 둘 다 참이어야 참
!x // x가 거짓이면 참
money = 1000
candy = 200
point = 10
if money < candy or point > 7:
print('캔디를 살 수 있습니다.')
else:
print('캔디를 살 수 없습니다.')
int money = 1000;
int candy = 200;
int point = 10;
if (money < candy || point > 7) {
printf("캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
money = 5
candy = 7
point = 2
if money > candy:
print('1-캔디를 살 수 있습니다.')
elif money == candy:
print('2-캔디를 살 수 있습니다.')
elif point >= 2:
print('3-캔디를 살 수 있습니다.')
else:
print('캔디를 살 수 없습니다.')
int money = 5;
int candy = 7;
int point = 2;
if (money > candy) {
printf("1-캔디를 살 수 있습니다.\n");
} else if (money == candy) {
printf("2-캔디를 살 수 있습니다.\n");
} else if (point >= 2) {
printf("3-캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
a = ['apple', 2021, 'Z', 10, 90, 'yellow']
if 'Z' in a:
print('Z가 들어 있으므로 실행됩니다.')
a = int(input('정수 입력: '))
b = int(input('정수 입력: '))
c = int(input('정수 입력: '))
if a > b and a > c:
print('가장 큰 수:', a)
elif b > a and b > c:
print('가장 큰 수:', b)
else:
print('가장 큰 수:', c)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int a, b, c;
printf("정수 세 개 입력: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c)
printf("가장 큰 수: %d\n", a);
else if (b > a && b > c)
printf("가장 큰 수: %d\n", b);
else
printf("가장 큰 수: %d\n", c);
return 0;
}
score = 3
match score:
case 1:
print('C등급입니다.')
case 2:
print('B등급입니다.')
case 3:
print('A등급입니다.')
case _:
print('등급을 매길 수 없습니다.')
int score = 3;
switch (score) {
case 1:
printf("C등급입니다.\n");
break;
case 2:
printf("B등급입니다.\n");
break;
case 3:
printf("A등급입니다.\n");
break;
default:
printf("등급을 매길 수 없습니다.\n");
}
clear = 0
while clear < 5:
print(f'게임을 {clear}번 클리어했습니다.')
clear = clear + 1
if clear == 5:
print('레벨이 올라갑니다.')
int clear = 0;
while (clear < 5) {
printf("게임을 %d번 클리어했습니다.\n",
clear);
clear = clear + 1;
if (clear == 5) {
printf("레벨이 올라갑니다.\n");
}
}
cupramen = 4
while True:
money = int(input('돈을 넣으세요: '))
if money == 1500:
print('컵라면을 줍니다.')
cupramen -= 1
elif money > 1500:
print(f'거스름돈 {money-1500}원을 돌려줍니다.')
cupramen -= 1
else:
print('돈이 모자랍니다.')
if cupramen == 0:
print('컵라면이 다 떨어졌습니다.')
break
int cupramen = 4;
while (1) {
int money;
printf("돈을 넣으세요: ");
scanf("%d", &money);
if (money == 1500) {
printf("컵라면을 줍니다.\n");
cupramen--;
} else if (money > 1500) {
printf("거스름돈 %d원을 돌려줍니다.\n",
money - 1500);
cupramen--;
} else {
printf("돈이 모자랍니다.\n");
}
if (cupramen == 0) {
printf("컵라면이 다 떨어졌습니다.\n");
break;
}
}
people = int(input('학생 수: '))
count = 1
sum = 0
while count <= people:
num = int(input(f'{count}번 점수: '))
sum += num
count += 1
print(f'총합: {sum}')
print(f'평균: {sum / people}')
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int people, count = 1, sum = 0, num;
printf("학생 수: ");
scanf("%d", &people);
while (count <= people) {
printf("%d번 점수: ", count);
scanf("%d", &num);
sum += num;
count++;
}
printf("총합: %d\n", sum);
printf("평균: %.2f\n",
(float)sum / people);
return 0;
}
list = ['a', 'b', 'c']
for z in list:
print(z, end=' ')
int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
# range 사용법
range(5) # 0 1 2 3 4
range(1, 6) # 1 2 3 4 5
range(1, 10, 2)# 1 3 5 7 9 (2칸씩)
a = [12, 13, 14, 15, 16, 17]
for b in a: # 값을 직접 꺼냄
if b % 2 == 0:
print(b, end=' ')
int a[] = {12,13,14,15,16,17};
int i;
for (i = 0; i < 6; i++) {
if (a[i] % 2 == 0)
printf("%d ", a[i]);
}
num = int(input('정수 입력: '))
sum = 0
for a in range(1, num + 1):
sum += a
print(sum)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int num, sum = 0;
printf("정수 입력: ");
scanf("%d", &num);
for (int i = 1; i <= num; i++)
sum += i;
printf("%d\n", sum);
return 0;
}
i = 0
while i < 3:
j = 0
while j < 4:
print(j, end=' ')
j += 1
print()
i += 1
int i = 0;
while (i < 3) {
int j = 0;
while (j < 4) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}
a = [[1,2],[3,4,300,400],[5,6]]
for b in range(len(a)):
for c in range(len(a[b])):
print(a[b][c], end=' ')
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", j);
}
printf("\n");
}
for dan in range(2, 6):
print(f'=== {dan}단 ===')
for num in range(1, 10):
print(f'{dan} × {num} = {dan*num}')
int dan, num;
for (dan = 2; dan <= 5; dan++) {
printf("=== %d단 ===\n", dan);
for (num = 1; num <= 9; num++) {
printf("%d × %d = %d\n",
dan, num, dan*num);
}
}
# 숫자만
a = [1, 4, 8, 9, 13]
# 문자열만
b = ['I', 'love', 'python']
# 숫자와 문자열 섞기 — 파이썬만 가능
c = ['candy', 1, 'buy', 6, 'apple']
/* 방법 1: 크기와 함께 초기화 */
int a[5] = {1, 4, 8, 9, 13};
/* 방법 2: 크기 생략 — 개수가 자동으로 크기 */
int a[] = {1, 4, 8, 9, 13};
/* 방법 3: 크기만 선언, 나중에 채움 */
int a[5];
/* 방법 4: 일부만 초기화, 나머지는 0 */
int a[5] = {1, 4}; /* {1, 4, 0, 0, 0} */
a = [10, 20, 30, 40, 50]
print(a[0]) # 첫 번째
print(a[4]) # 마지막
print(a[2:4]) # 2번부터 3번까지
a[2] = 100 # 값 변경
print(a[2])
int a[5] = {10, 20, 30, 40, 50};
printf("%d\n", a[0]); // 첫 번째
printf("%d\n", a[4]); // 마지막
a[2] = 100; // 값 변경
printf("%d\n", a[2]);
a = [1, 4, 8, 9, 13]
# 방법 1: 값을 직접 꺼냄
for x in a:
print(x, end=' ')
# 방법 2: 인덱스로 접근
for i in range(len(a)):
print(a[i], end=' ')
int a[5] = {1, 4, 8, 9, 13};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
a = [34, 67, 43, 89, 55, 3, 45]
max_val = a[0]
for b in a:
if max_val < b:
max_val = b
print(max_val)
int a[] = {34, 67, 43, 89, 55, 3, 45};
int max_val = a[0];
int i;
for (i = 1; i < 7; i++) {
if (max_val < a[i])
max_val = a[i];
}
printf("%d\n", max_val);
a = [10, 20, 30, 40, 50]
total = 0
for x in a:
total += x
print(f'합: {total}')
print(f'평균: {total / len(a):.2f}')
int a[5] = {10, 20, 30, 40, 50};
int total = 0;
int i;
for (i = 0; i < 5; i++)
total += a[i];
printf("합: %d\n", total);
printf("평균: %.2f\n",
(float)total / 5);
a = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(a[0][0]) # 1행 1열
print(a[1][2]) # 2행 3열
print(a[2][3]) # 3행 4열
int a[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("%d\n", a[0][0]);
printf("%d\n", a[1][2]);
printf("%d\n", a[2][3]);
a = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
print()
int a[3][4] = {
{1,2,3,4},{5,6,7,8},{9,10,11,12}
};
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
scores = [
[85, 90, 78, 92],
[88, 76, 95, 87],
[92, 85, 90, 88]
]
for i in range(len(scores)):
total = sum(scores[i])
avg = total / len(scores[i])
print(f'{i+1}번 학생 평균: {avg:.2f}')
int scores[3][4] = {
{85,90,78,92},
{88,76,95,87},
{92,85,90,88}
};
int i, j, total;
for (i = 0; i < 3; i++) {
total = 0;
for (j = 0; j < 4; j++)
total += scores[i][j];
printf("%d번 학생 평균: %.2f\n",
i+1, (float)total/4);
}
a = {'name': 'kim', 'grade': 2, 'score': 88}
print(a['name']) # 키로 값 찾기
print(a['score'])
a['score'] = 95 # 기존 키 — 값 수정
a['subject'] = 'math' # 새 키 — 항목 추가
print(a)
a = {'name': 'kim', 'grade': 2, 'score': 88}
# 키만 순회
for key in a:
print(key, end=' ')
# 키와 값을 함께 순회
for key, val in a.items():
print(f'{key}: {val}')
students = {
'kim': 88,
'lee': 75,
'park': 92
}
# 평균 계산
total = 0
for score in students.values():
total += score
avg = total / len(students)
print(f'평균: {avg:.1f}')
# 90점 이상 출력
for name, score in students.items():
if score >= 90:
print(f'{name}: {score}점')
a = 'Hello'
print(a)
// 방법 1: 크기 생략
char a[] = "Hello";
// 방법 2: 크기 지정
char a[10] = "Hello";
// 방법 3: 문자 배열로 직접
char a[] = {'H','e','l','l','o','\0'};
/* 인덱스: 0 1 2 3 4 5 */
/* 값: 'H' 'e' 'l' 'l' 'o' '\0' */
char str[] = "Hello";
printf("%c\n", str[0]); // H
printf("%c\n", str[4]); // o
a = 'Hello'
b = "World" # 큰따옴표도 같음
c = 'Hello' + 'World' # 이어붙이기
d = 'Hello' * 3 # 반복
print(c)
print(d)
#include <string.h>
char a[] = "Hello";
char b[10] = "World";
/* 이어붙이기 — 연산자로 안 됨, 함수 필요 */
char c[20] = "Hello";
strcat(c, "World");
printf("%s\n", c);
/* 반복 — C엔 기본 문법 없음 */
name = input('이름을 입력하세요: ')
age = int(input('나이를 입력하세요: '))
print(f'안녕하세요, {name}님!')
print(f'당신은 {age}살입니다.')
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
char name[20];
int age;
printf("이름을 입력하세요: ");
scanf("%s", name); /* & 없이 사용 */
printf("나이를 입력하세요: ");
scanf("%d", &age);
printf("안녕하세요, %s님!\n", name);
printf("당신은 %d살입니다.\n", age);
return 0;
}
a = 'Hello'
print(len(a)) # 5
#include <string.h>
char a[] = "Hello";
printf("%d\n", (int)strlen(a)); // 5
a = 'Hello'
b = a # 그냥 대입하면 됨
print(b)
char a[] = "Hello";
char b[20];
strcpy(b, a); /* a를 b에 복사 */
printf("%s\n", b);
a = 'Hello'
b = 'World'
print(a + b) # HelloWorld
print(a + ' ' + b) # Hello World
char a[20] = "Hello";
char b[] = "World";
strcat(a, b);
printf("%s\n", a); // HelloWorld
a = 'Hello'
b = 'Hello'
if a == b:
print('같습니다.')
char a[] = "Hello";
char b[] = "Hello";
if (strcmp(a, b) == 0) {
printf("같습니다.\n");
}
a = 'Hello World'
print(a.upper()) # 전부 대문자
print(a.lower()) # 전부 소문자
print(a.replace('World', 'Python'))
print(a.split(' ')) # 공백으로 나누기
print('llo' in a) # 포함 여부
a = 'Hello'
for ch in a:
print(ch, end=' ')
char a[] = "Hello";
int i;
for (i = 0; a[i] != '\0'; i++) {
printf("%c ", a[i]);
}
a = 'Hello World'
count = 0
for ch in a:
if ch.isupper():
count += 1
print(f'대문자 개수: {count}')
char a[] = "Hello World";
int i, count = 0;
for (i = 0; a[i] != '\0'; i++) {
if (a[i] >= 'A' && a[i] <= 'Z')
count++;
}
printf("대문자 개수: %d\n", count);
a = 'Hello World'
target = 'l'
count = a.count(target)
print(f"'{target}'의 개수: {count}")
char a[] = "Hello World";
char target = 'l';
int i, count = 0;
for (i = 0; a[i] != '\0'; i++) {
if (a[i] == target)
count++;
}
printf("'%c'의 개수: %d\n",
target, count);
names = ['홍길동', '김철수', '이영희']
for i, name in enumerate(names):
print(f'{i+1}번: {name}')
char names[3][20] = {
"홍길동", "김철수", "이영희"
};
int i;
for (i = 0; i < 3; i++) {
printf("%d번: %s\n",
i+1, names[i]);
}
def add(a, b):
return a + b
result = add(10, 20)
print(result)
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
printf("%d\n", result);
return 0;
}
def hello():
print('Hello!')
hello()
void hello() {
printf("Hello!\n");
}
hello();
def get_number():
return 100
num = get_number()
print(num)
int get_number() {
return 100;
}
int num = get_number();
printf("%d\n", num);
def print_sum(a, b):
print(a + b)
print_sum(40, 50)
void print_sum(int a, int b) {
printf("%d\n", a + b);
}
print_sum(40, 50);
def add(a, b):
return a + b
result = add(40, 50)
print(result)
int add(int a, int b) {
return a + b;
}
int result = add(40, 50);
printf("%d\n", result);
def calc(a, b):
return a + b, a * b, a - b
print(calc(4, 6))
def is_even(num):
if num % 2 == 0:
return True
else:
return False
num = int(input('정수 입력: '))
if is_even(num):
print('짝수입니다.')
else:
print('홀수입니다.')
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int is_even(int num) {
if (num % 2 == 0) return 1;
else return 0;
}
int main() {
int num;
printf("정수 입력: ");
scanf("%d", &num);
if (is_even(num))
printf("짝수입니다.\n");
else
printf("홀수입니다.\n");
return 0;
}
def add(x, y):
return x + y
def mul(a, b):
c = a * b
d = a + b
e = add(c, d) # add 함수 호출
return e / 2
print(mul(2, 3))
#include <stdio.h>
int add(int x, int y) {
return x + y;
}
float mul(int a, int b) {
int c = a * b;
int d = a + b;
int e = add(c, d); /* add 호출 */
return (float)e / 2;
}
int main() {
printf("%.1f\n", mul(2, 3));
return 0;
}
def max_score(scores):
m = scores[0]
for s in scores:
if m < s: m = s
return m
def min_score(scores):
m = scores[0]
for s in scores:
if m > s: m = s
return m
def gap(scores):
return max_score(scores) - min_score(scores)
points = [9.5, 8.8, 7.0, 7.9, 10.0]
print(gap(points))
#include <stdio.h>
float max_score(float s[], int n) {
float m = s[0]; int i;
for (i=1; i<n; i++)
if (m < s[i]) m = s[i];
return m;
}
float min_score(float s[], int n) {
float m = s[0]; int i;
for (i=1; i<n; i++)
if (m > s[i]) m = s[i];
return m;
}
float gap(float s[], int n) {
return max_score(s,n) - min_score(s,n);
}
int main() {
float p[] = {9.5,8.8,7.0,7.9,10.0};
printf("%.1f\n", gap(p, 5));
return 0;
}
def count(a):
if a == 0: # 종료 조건
return
print(a, end=' ')
count(a - 1) # 자기 자신 호출
count(5)
void count(int a) {
if (a == 0) return; /* 종료 조건 */
printf("%d ", a);
count(a - 1); /* 자기 자신 호출 */
}
count(5);
def count(a):
if a == 0:
return
a -= 1
count(a) # 먼저 재귀 호출
print(a, end=' ') # 나중에 출력
count(5)
void count(int a) {
if (a == 0) return;
a--;
count(a); /* 먼저 재귀 호출 */
printf("%d ", a); /* 나중에 출력 */
}
count(5);
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(10))
int sum_to(int n) {
if (n == 0) return 0;
return n + sum_to(n - 1);
}
printf("%d\n", sum_to(10));
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(10))
int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
printf("%d\n", factorial(10));
a = 10
b = a # b도 같은 값을 가리킴
print(id(a), id(b)) # 같은 주소
b = 20 # b는 이제 다른 값을 가리킴
print(id(a), id(b)) # 다른 주소
print(a) # a는 여전히 10
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a; /* 포인터 선언 */
printf("a의 값: %d\n", a);
printf("a의 주소: %p\n", &a);
printf("ptr이 저장한 주소: %p\n", ptr);
printf("ptr이 가리키는 값: %d\n", *ptr);
return 0;
}
int a = 10;
int *ptr = &a;
*ptr = 20; /* 포인터로 값 변경 */
printf("%d\n", a); /* a도 20이 됨 */
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; /* 배열 이름 = 첫 요소 주소 */
/* 세 가지 방식 — 결과 모두 같음 */
printf("%d\n", arr[2]); /* 배열 인덱스 */
printf("%d\n", *(arr + 2)); /* 포인터 연산 */
printf("%d\n", *(ptr + 2)); /* 포인터 변수 */
a = [10, 20, 30, 40, 50]
print(a[2]) # 30
print(id(a[2])) # 30이 저장된 주소
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("%d\n", *ptr); /* 10 */
printf("%d\n", *(ptr + 1)); /* 20 */
printf("%d\n", *(ptr + 2)); /* 30 */
ptr++; /* 다음 요소로 이동 */
printf("%d\n", *ptr); /* 20 */
void swap_val(int a, int b) {
int temp = a;
a = b;
b = temp;
/* 함수 안에서만 바뀌고 끝 */
}
int x = 3, y = 7;
swap_val(x, y);
printf("%d %d\n", x, y); /* 3 7 — 안 바뀜 */
void swap_ptr(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int x = 3, y = 7;
swap_ptr(&x, &y);
printf("%d %d\n", x, y); /* 7 3 — 바뀜 */
def change(a):
a = 99 # 함수 안에서만 바뀜
x = 10
change(x)
print(x) # 10 — 안 바뀜
def add_item(lst):
lst.append(99) # 원본 리스트에 직접 추가
a = [1, 2, 3]
add_item(a)
print(a) # [1, 2, 3, 99] — 바뀜
def total(lst):
s = 0
for x in lst:
s += x
return s
a = [1, 2, 3, 4, 5]
print(total(a))
int total(int arr[], int size) {
int s = 0, i;
for (i = 0; i < size; i++)
s += arr[i];
return s;
}
int total(int *p, int size) {
int s = 0, i;
for (i = 0; i < size; i++)
s += *(p + i);
return s;
}
int arr[] = {1, 2, 3, 4, 5};
printf("%d\n", total(arr, 5));
# 파이썬은 교환이 한 줄
x, y = 3, 7
x, y = y, x
print(x, y) # 7 3
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 3, y = 7;
printf("전: %d %d\n", x, y);
swap(&x, &y);
printf("후: %d %d\n", x, y);
return 0;
}
class Student:
name = ''
age = 0
score = 0
s1 = Student() # 인스턴스 생성
s1.name = '홍길동'
s1.age = 20
s1.score = 95
print(s1.name, s1.age, s1.score)
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
int score;
};
int main() {
struct Student s1;
strcpy(s1.name, "홍길동");
s1.age = 20;
s1.score = 95;
printf("%s %d %d\n",
s1.name, s1.age, s1.score);
return 0;
}
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s1 = Student('홍길동', 20, 95)
s2 = Student('김철수', 19, 88)
print(s1.name, s1.score)
print(s2.name, s2.score)
struct Student s1 = {"홍길동", 20, 95};
struct Student s2 = {"김철수", 19, 88};
printf("%s %d\n", s1.name, s1.score);
printf("%s %d\n", s2.name, s2.score);
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def introduce(self): # 인스턴스 메서드
print(f'{self.name}의 점수: {self.score}')
def is_pass(self):
if self.score >= 60:
print(f'{self.name}: 합격')
else:
print(f'{self.name}: 불합격')
s1 = Student('홍길동', 95)
s2 = Student('김철수', 45)
s1.introduce()
s1.is_pass()
s2.is_pass()
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
void introduce(struct Student s) {
printf("%s의 점수: %d\n",
s.name, s.score);
}
void is_pass(struct Student s) {
if (s.score >= 60)
printf("%s: 합격\n", s.name);
else
printf("%s: 불합격\n", s.name);
}
int main() {
struct Student s1 = {"홍길동", 95};
struct Student s2 = {"김철수", 45};
introduce(s1);
is_pass(s1);
is_pass(s2);
return 0;
}
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [
Student('김철수', 85),
Student('이영희', 92),
Student('박민수', 78),
]
for s in students:
print(f'{s.name}: {s.score}점')
struct Student students[3] = {
{"김철수", 85},
{"이영희", 92},
{"박민수", 78},
};
int i;
for (i = 0; i < 3; i++) {
printf("%s: %d점\n",
students[i].name,
students[i].score);
}
class Game: # 부모 클래스
def start(self):
print('게임을 시작합니다.')
class Player(Game): # Game 을 상속
def select(self):
print('캐릭터를 고르세요.')
user1 = Player()
user1.start() # 부모 메서드 사용 가능
user1.select()
class Game:
def __init__(self):
self.hi = '안녕!'
print('게임을 시작합니다.')
class Player(Game):
def __init__(self):
print('캐릭터를 고르세요.')
super().__init__() # 부모 생성자 호출
self.name = '신호등'
user1 = Player()
print(user1.name)
print(user1.hi) # 부모 데이터도 사용 가능
class Game:
def greet(self):
print('안녕')
class User(Game):
def greet(self): # 오버라이딩
print('hi, how are you?')
def greet_parent(self):
super().greet() # 부모 메서드 호출
one = User()
one.greet() # 자식 메서드 실행
one.greet_parent() # 부모 메서드 실행
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def plus(self): return self.a + self.b
def minus(self): return self.a - self.b
def mul(self): return self.a * self.b
def div(self): return self.a / self.b
c = Calculator(10, 20)
print(c.plus(), c.minus(), c.mul(), c.div())
#include <stdio.h>
struct Calc { int a; int b; };
int plus (struct Calc c) { return c.a+c.b; }
int minus(struct Calc c) { return c.a-c.b; }
int mul (struct Calc c) { return c.a*c.b; }
float div (struct Calc c) {
return (float)c.a/c.b;
}
int main() {
struct Calc c = {10, 20};
printf("%d %d %d %.1f\n",
plus(c), minus(c),
mul(c), div(c));
return 0;
}

유니티(Unity)를 시작하려는 분들을 위해 만들어진 책이지만, 이 책에서는 유니티 화면을 다루지 않습니다. 순수하게 C# 문법만 실습합니다. 유니티를 다루는 데 실제로 필요한 개념만 뽑아서 담았습니다. 요즘은 AI로 스크립트( C#코드)도 편리하게 만들 수 있습니다. 이 책은 상세한 설명보다 실습을 해보는 것에 초점을 두었습니다. 처음 보는 용어가 나온다면 본문에는 자세한 설명이 없을 수 있으니 인터넷으로 검색해 보기 바랍니다.
using System;
class Program
{
static void Main()
{
// 여기서 코드를 작성합니다
}
}
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello C#");
}
}
using System;
class Program
{
static void Main()
{
int a;
a = 10;
}
}
using System;
class Program
{
static void Main()
{
int a = 10;
int b = 20;
int c = a + b;
Console.WriteLine(c);
}
}
using System;
class Program
{
static void Main()
{
int a = 10; // 정수
int b = -20; // 음수
float c = 0.2f; // 실수 (f를 붙임)
double d = -3.0; // 더 정밀한 실수
Console.WriteLine(a + b);
Console.WriteLine(c);
Console.WriteLine(d);
}
}
using System;
class Program
{
static void Main()
{
int money = 5000;
int apple = 800;
int count = money / apple;
Console.WriteLine(count);
}
}
using System;
class Program
{
static void Main()
{
char grade = 'A';
string name = "홍길동";
Console.WriteLine(grade);
Console.WriteLine(name);
}
}
using System;
class Program
{
static void Main()
{
bool isJumping = false;
Console.WriteLine(isJumping);
isJumping = true;
Console.WriteLine(isJumping);
}
}
using System;
class Program
{
static void Main()
{
Console.Write("이름을 입력하세요: ");
string name = Console.ReadLine();
Console.WriteLine("안녕하세요, " + name + "님!");
}
}
using System;
class Program
{
static void Main()
{
Console.Write("나이를 입력하세요: ");
string input = Console.ReadLine();
int age = int.Parse(input);
Console.WriteLine(age + 1);
}
}
using System;
class Program
{
static void Main()
{
int a = 10;
double b = a; // 암시적 변환 (int → double)
Console.WriteLine(b);
double c = 3.7;
int d = (int)c; // 명시적 변환 (double → int)
Console.WriteLine(d);
}
}
using System;
class Program
{
static void Main()
{
const int MaxHp = 100;
Console.WriteLine(MaxHp);
}
}
using System;
class Program
{
static void Main()
{
int money = 1000;
int candy = 200;
if (money > candy)
{
Console.WriteLine("캔디를 살 수 있습니다.");
}
else
{
Console.WriteLine("캔디를 살 수 없습니다.");
}
}
}
using System;
class Program
{
static void Main()
{
int money = 1000;
int candy = 200;
int point = 10;
if (money < candy || point > 7)
{
Console.WriteLine("캔디를 살 수 있습니다.");
}
else
{
Console.WriteLine("캔디를 살 수 없습니다.");
}
}
}
using System;
class Program
{
static void Main()
{
int money = 5;
int candy = 7;
int point = 2;
if (money > candy)
{
Console.WriteLine("1-캔디를 살 수 있습니다.");
}
else if (money == candy)
{
Console.WriteLine("2-캔디를 살 수 있습니다.");
}
else if (point >= 2)
{
Console.WriteLine("3-캔디를 살 수 있습니다.");
}
else
{
Console.WriteLine("캔디를 살 수 없습니다.");
}
}
}
using System;
class Program
{
static void Main()
{
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
if (age >= 20)
Console.WriteLine("성인");
else
Console.WriteLine("미성년자");
}
}
using System;
class Program
{
static void Main()
{
Console.Write("첫 번째 정수: ");
int a = int.Parse(Console.ReadLine());
Console.Write("두 번째 정수: ");
int b = int.Parse(Console.ReadLine());
Console.Write("세 번째 정수: ");
int c = int.Parse(Console.ReadLine());
if (a > b && a > c)
Console.WriteLine("가장 큰 수는 " + a + "입니다.");
else if (b > a && b > c)
Console.WriteLine("가장 큰 수는 " + b + "입니다.");
else
Console.WriteLine("가장 큰 수는 " + c + "입니다.");
}
}
using System;
class Program
{
static void Main()
{
int score = 3;
switch (score)
{
case 1:
Console.WriteLine("C등급입니다.");
break;
case 2:
Console.WriteLine("B등급입니다.");
break;
case 3:
Console.WriteLine("A등급입니다.");
break;
default:
Console.WriteLine("등급을 매길 수 없습니다.");
break;
}
}
}
using System;
class Program
{
static void Main()
{
Console.Write("메뉴를 선택하세요 (1-3): ");
int menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
Console.WriteLine("햄버거를 선택하셨습니다.");
break;
case 2:
Console.WriteLine("피자를 선택하셨습니다.");
break;
case 3:
Console.WriteLine("치킨을 선택하셨습니다.");
break;
default:
Console.WriteLine("잘못된 선택입니다.");
break;
}
}
}
using System;
class Program
{
static void Main()
{
int clear = 0;
while (clear < 5)
{
Console.WriteLine("현재까지 게임을 " + clear + "번 클리어 했습니다.");
clear = clear + 1;
if (clear == 5)
{
Console.WriteLine("레벨이 올라갑니다.");
}
}
}
}
using System;
class Program
{
static void Main()
{
int cupramen = 4;
while (true)
{
Console.Write("돈을 넣으세요: ");
int money = int.Parse(Console.ReadLine());
if (money == 1500)
{
Console.WriteLine("컵라면을 줍니다");
cupramen = cupramen - 1;
}
else if (money > 1500)
{
Console.WriteLine("컵라면을 주고, 거스름돈 " + (money - 1500) + "원을 돌려 줍니다");
cupramen = cupramen - 1;
}
else
{
Console.WriteLine("돈이 모자랍니다. 돈을 돌려줍니다");
}
if (cupramen == 0)
{
Console.WriteLine("컵라면이 다 떨어졌습니다.");
break;
}
}
}
}
using System;
class Program
{
static void Main()
{
int sum = 0;
while (true)
{
Console.Write("숫자를 입력하세요 (0 입력 시 종료): ");
int num = int.Parse(Console.ReadLine());
if (num == 0) break;
sum += num;
}
Console.WriteLine("총합: " + sum);
}
}
using System;
class Program
{
static void Main()
{
Console.Write("학생수를 입력하시오: ");
int people = int.Parse(Console.ReadLine());
int count = 1;
int sum = 0;
while (count <= people)
{
Console.Write(count + "번 학생의 점수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
sum += num;
count++;
}
Console.WriteLine("총합계는 " + sum + "입니다.");
Console.WriteLine("평균은 " + ((double)sum / people) + "입니다.");
}
}
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 5; i++)
{
Console.Write(i + " ");
}
}
}
using System;
class Program
{
static void Main()
{
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= num; i++)
{
sum += i;
}
Console.WriteLine("합: " + sum);
}
}
using System;
class Program
{
static void Main()
{
int i = 0;
while (i < 3)
{
int j = 0;
while (j < 4)
{
Console.Write(j + " ");
j++;
}
Console.WriteLine();
i++;
}
}
}
using System;
class Program
{
static void Main()
{
int i = 1;
while (i <= 3)
{
int j = 1;
while (j <= i)
{
Console.Write("*");
j++;
}
Console.WriteLine();
i++;
}
}
}
using System;
class Program
{
static void Main()
{
int dan = 2;
while (dan <= 5)
{
int num = 1;
Console.WriteLine("=== " + dan + "단 ===");
while (num <= 9)
{
Console.WriteLine(dan + " x " + num + " = " + (dan * num));
num++;
}
Console.WriteLine();
dan++;
}
}
}
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
}
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
// 공백 출력
for (int j = 1; j <= 5 - i; j++)
{
Console.Write(" ");
}
// 숫자 출력
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write(k);
}
Console.WriteLine();
}
}
}
// 배열을 사용하지 않을 때
int score1 = 85;
int score2 = 90;
int score3 = 78;
int score4 = 92;
int score5 = 88;
// 배열을 사용할 때
int[] score = { 85, 90, 78, 92, 88 };
// 방법 1: new로 크기만 지정 (모든 요소가 0으로 채워짐)
int[] arr1 = new int[5];
// 방법 2: 값과 함께 초기화 (크기는 자동으로 결정)
int[] arr2 = { 10, 20, 30, 40, 50 };
// 방법 3: new와 값을 함께 사용
int[] arr3 = new int[] { 1, 2, 3 };
using System;
class Program
{
static void Main()
{
int[] arr1 = new int[5];
int[] arr2 = { 10, 20, 30, 40, 50 };
Console.WriteLine(arr1[0]); // 기본값 0
Console.WriteLine(arr2[0]);
Console.WriteLine(arr2.Length); // 배열의 크기
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(arr.Length);
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine(arr[0]); // 첫 번째 요소
Console.WriteLine(arr[1]); // 두 번째 요소
Console.WriteLine(arr[4]); // 마지막 요소
arr[2] = 100; // 요소 값 변경
Console.WriteLine(arr[2]);
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 1, 4, 8, 9, 13 };
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 34, 67, 43, 89, 55, 3, 45 };
int max = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
Console.WriteLine("가장 큰 수는 " + max + "입니다.");
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 10, 20, 30, 40, 50 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
double average = (double)sum / arr.Length;
Console.WriteLine("합: " + sum);
Console.WriteLine("평균: " + average);
}
}
using System;
class Program
{
static void Main()
{
int[] arr = { 1, 4, 8, 9, 13 };
foreach (int num in arr)
{
Console.Write(num + " ");
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> scoreList = new List<int>();
scoreList.Add(85);
scoreList.Add(90);
scoreList.Add(78);
Console.WriteLine(scoreList.Count); // 리스트의 개수
Console.WriteLine(scoreList[0]); // 인덱스로 접근
scoreList.Remove(90); // 값 90 제거
Console.WriteLine(scoreList.Count);
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> items = new List<string>();
items.Add("포션");
items.Add("검");
items.Add("방패");
foreach (string item in items)
{
Console.WriteLine(item);
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> scoreList = new List<int>();
for (int i = 1; i <= 5; i++)
{
Console.Write(i + "번째 점수: ");
int score = int.Parse(Console.ReadLine());
scoreList.Add(score);
}
int sum = 0;
foreach (int score in scoreList)
{
sum += score;
}
double average = (double)sum / scoreList.Count;
Console.WriteLine("합계: " + sum);
Console.WriteLine("평균: " + average);
}
}
using System;
class Program
{
static void Main()
{
// 2차원 배열 선언: 3행 4열 (C#은 콤마로 구분합니다)
int[,] arr = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
Console.WriteLine(arr[0, 0]); // 첫 번째 행, 첫 번째 열
Console.WriteLine(arr[1, 2]); // 두 번째 행, 세 번째 열
Console.WriteLine(arr[2, 3]); // 세 번째 행, 네 번째 열
}
}
using System;
class Program
{
static void Main()
{
string name = "홍길동";
int age = 20;
Console.WriteLine(name + "님은 " + age + "살입니다.");
}
}
using System;
class Program
{
static void Main()
{
string name = "홍길동";
int age = 20;
Console.WriteLine($"{name}님은 {age}살입니다.");
}
}
using System;
class Program
{
static void Main()
{
Console.Write("이름을 입력하세요: ");
string name = Console.ReadLine();
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine($"안녕하세요, {name}님! 당신은 {age}살입니다.");
}
}
using System;
class Program
{
static void Main()
{
string str = " Hello World ";
Console.WriteLine(str.Length);
Console.WriteLine(str.Trim());
Console.WriteLine(str.ToUpper());
Console.WriteLine(str.ToLower());
Console.WriteLine(str.Contains("World"));
Console.WriteLine(str.Replace("World", "C#"));
}
}
using System;
class Program
{
static void Main()
{
string str1 = "Hello";
string str2 = "Hello";
if (str1 == str2)
{
Console.WriteLine("문자열이 같습니다.");
}
else
{
Console.WriteLine("문자열이 다릅니다.");
}
}
}
using System;
class Program
{
static void Main()
{
string word = "UnityEngine";
Console.WriteLine(word.Substring(0, 5)); // 0번부터 5글자
string sentence = "나는 유니티를 배운다";
string[] words = sentence.Split(' ');
foreach (string w in words)
{
Console.WriteLine(w);
}
}
}
using System;
class Program
{
static void Main()
{
string str = "Hello";
foreach (char ch in str)
{
Console.Write(ch + " ");
}
}
}
using System;
class Program
{
static void Main()
{
string str = "Hello World";
int count = 0;
foreach (char ch in str)
{
if (char.IsUpper(ch))
{
count++;
}
}
Console.WriteLine("대문자 개수: " + count);
}
}
using System;
class Program
{
static void Main()
{
string[] names = { "홍길동", "김철수", "이영희" };
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{i + 1}번: {names[i]}");
}
}
}
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string>();
for (int i = 1; i <= 3; i++)
{
Console.Write($"{i}번 이름: ");
names.Add(Console.ReadLine());
}
Console.WriteLine();
Console.WriteLine("입력한 이름:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
using System;
class Program
{
// 함수 정의
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(10, 20); // 함수 호출
Console.WriteLine(result);
}
}
using System;
class Program
{
// 형태 1: 매개변수 없고, 리턴 값 없음
static void PrintHello()
{
Console.WriteLine("Hello!");
}
// 형태 2: 매개변수 없고, 리턴 값 있음
static int GetNumber()
{
return 100;
}
// 형태 3: 매개변수 있고, 리턴 값 없음
static void PrintSum(int a, int b)
{
Console.WriteLine(a + b);
}
// 형태 4: 매개변수 있고, 리턴 값 있음
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
PrintHello();
int num = GetNumber();
Console.WriteLine(num);
PrintSum(40, 50);
int result = Add(40, 50);
Console.WriteLine(result);
}
}
using System;
class Program
{
static bool IsEven(int num)
{
if (num % 2 == 0)
return true;
else
return false;
}
static void Main()
{
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
if (IsEven(num))
Console.WriteLine("짝수입니다.");
else
Console.WriteLine("홀수입니다.");
}
}
using System;
class Program
{
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
PrintArray(arr);
}
}
using System;
class Program
{
static void DoubleArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = arr[i] * 2; // 원본 배열 수정
}
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
Console.Write("원본: ");
foreach (int num in arr) Console.Write(num + " ");
Console.WriteLine();
DoubleArray(arr);
Console.Write("변경 후: ");
foreach (int num in arr) Console.Write(num + " ");
Console.WriteLine();
}
}
using System;
class Program
{
static void TryChange(int num)
{
num = 999; // 복사본만 바뀜
}
static void Main()
{
int x = 10;
TryChange(x);
Console.WriteLine(x); // 여전히 10
}
}
using System;
class Program
{
static int SumArray(int[] arr)
{
int sum = 0;
foreach (int num in arr)
{
sum += num;
}
return sum;
}
static void Main()
{
int[] arr = { 10, 20, 30, 40, 50 };
int total = SumArray(arr);
Console.WriteLine("합: " + total);
}
}
using System;
class Program
{
static void Count(int a)
{
if (a == 0)
{
return; // 종료 조건
}
Console.Write(a + " ");
Count(a - 1); // 자기 자신 호출
}
static void Main()
{
Count(5);
}
}
using System;
class Program
{
static int Sum(int n)
{
if (n == 0)
{
return 0; // 종료 조건
}
return n + Sum(n - 1); // n + (n-1까지의 합)
}
static void Main()
{
int result = Sum(10);
Console.WriteLine("1부터 10까지의 합: " + result);
}
}
// 클래스를 사용하지 않을 때
string name;
int age;
int score;
// 클래스를 사용할 때
class Student
{
public string name;
public int age;
public int score;
}
using System;
class Student
{
public string name;
public int age;
public int score;
}
class Program
{
static void Main()
{
Student s1 = new Student();
s1.name = "홍길동";
s1.age = 20;
s1.score = 95;
Console.WriteLine($"이름: {s1.name}, 나이: {s1.age}, 점수: {s1.score}");
}
}
class Player
{
public string name; // 클래스 밖에서 접근 가능
private int hp; // 클래스 안에서만 접근 가능
}
using System;
class Student
{
public string name;
public int age;
// 생성자: 클래스와 이름이 같고, 반환 타입이 없습니다
public Student(string name, int age)
{
this.name = name;
this.age = age;
}
}
class Program
{
static void Main()
{
Student s1 = new Student("홍길동", 20);
Console.WriteLine($"이름: {s1.name}, 나이: {s1.age}");
}
}
using System;
class Player
{
private int hp;
public int Hp
{
get { return hp; }
set { hp = value < 0 ? 0 : value; } // 음수가 되지 않도록 방지
}
}
class Program
{
static void Main()
{
Player p = new Player();
p.Hp = -10;
Console.WriteLine(p.Hp);
}
}
using System;
class Player
{
private string name;
public string Name
{
get { return name; }
set
{
if (value == "")
name = "이름없음"; // 빈 값이면 기본 이름으로
else
name = value;
}
}
}
class Program
{
static void Main()
{
Player p = new Player();
p.Name = ""; // 빈 값을 넣어 봄
Console.WriteLine(p.Name);
p.Name = "홍길동";
Console.WriteLine(p.Name);
}
}
public int Hp { get; set; }
using System;
class Monster
{
public static int count = 0; // 모든 몬스터가 공유하는 값
public Monster()
{
count++;
}
}
class Program
{
static void Main()
{
new Monster();
new Monster();
new Monster();
Console.WriteLine(Monster.count);
}
}
using System;
class Animal
{
public string name;
public void Eat()
{
Console.WriteLine(name + "가 먹이를 먹습니다.");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine(name + "가 짖습니다.");
}
}
class Program
{
static void Main()
{
Dog d = new Dog();
d.name = "초코";
d.Eat(); // Animal에게서 물려받은 함수
d.Bark(); // Dog 자신의 함수
}
}
public class Player : MonoBehaviour
{
void Start() { ... }
void Update() { ... }
}
enum State
{
Idle,
Run,
Jump
}
using System;
enum State
{
Idle,
Run,
Jump
}
class Program
{
static void Main()
{
State current = State.Idle;
Console.WriteLine(current);
current = State.Jump;
Console.WriteLine(current);
}
}
using System;
enum State
{
Idle,
Run,
Jump
}
class Program
{
static void Main()
{
State current = State.Run;
switch (current)
{
case State.Idle:
Console.WriteLine("가만히 있습니다.");
break;
case State.Run:
Console.WriteLine("달리고 있습니다.");
break;
case State.Jump:
Console.WriteLine("점프 중입니다.");
break;
}
}
}
struct Point
{
public int x;
public int y;
}
using System;
struct Point
{
public int x;
public int y;
}
class Program
{
static void Main()
{
Point p1 = new Point();
p1.x = 10;
p1.y = 20;
Console.WriteLine($"({p1.x}, {p1.y})");
}
}
using System;
struct PointS { public int x; }
class PointC { public int x; }
class Program
{
static void Main()
{
PointS s1 = new PointS();
s1.x = 10;
PointS s2 = s1; // 값이 복사됨
s2.x = 99;
Console.WriteLine(s1.x); // 10, 그대로
PointC c1 = new PointC();
c1.x = 10;
PointC c2 = c1; // 참조가 공유됨
c2.x = 99;
Console.WriteLine(c1.x); // 99, 같이 바뀜
}
}
using System;
struct Point
{
public int x;
public int y;
}
class Program
{
static Point AddPoints(Point p1, Point p2)
{
Point result = new Point();
result.x = p1.x + p2.x;
result.y = p1.y + p2.y;
return result;
}
static void Main()
{
Point p1 = new Point();
p1.x = 10;
p1.y = 20;
Point p2 = new Point();
p2.x = 30;
p2.y = 40;
Point sum = AddPoints(p1, p2);
Console.WriteLine($"합: ({sum.x}, {sum.y})");
}
}
using UnityEngine;
using System.Collections.Generic;
public enum PlayerState
{
Idle,
Run,
Jump
}
public class Player : MonoBehaviour
{
public int Hp { get; set; } = 100;
public float speed = 5f;
private PlayerState state = PlayerState.Idle;
private List<string> items = new List<string>();
void Start()
{
items.Add("포션");
Debug.Log($"게임 시작! HP: {Hp}");
}
void Update()
{
if (Hp <= 0)
{
state = PlayerState.Idle;
Debug.Log("플레이어가 쓰러졌습니다.");
}
switch (state)
{
case PlayerState.Run:
transform.Translate(Vector3.forward * speed * Time.deltaTime);
break;
}
}
void TakeDamage(int damage)
{
Hp -= damage;
}
}

이 책은 코딩을 처음 접하는 독자가 생성형 AI에게 원하는 내용을 말로 지시하고, 완성된 홈페이지를 인터넷에 공개하기까지의 과정을 차근차근 안내하는 실습서입니다. 어려운 명령어나 코드를 외우는 대신 소개 페이지, 가게 홍보 페이지, 여행 사진 갤러리, 경비 정산 기능을 직접 만들며 바이브코딩을 경험합니다. 실습에 필요한 지시문과 완성 HTML 파일도 함께 제공하여, 막히더라도 완성본과 비교하며 끝까지 따라갈 수 있습니다.
같은 부탁을 해도 결과 화면은 조금씩 다르게 나옵니다. 정상입니다.
“제 소개 페이지를 만들어줘. 이름은 박서준이고, 취미는 텃밭 가꾸기, 좋아하는 색은 초록색이야. 제 사진을 넣을 자리도 만들어줘.”
"숲마루공방이라는 목공방 홍보 페이지를 만들어줘. 소개, 제품, 오시는 길 이렇게 세 부분으로 나누고, 위쪽에 이 세 곳으로 바로 이동할 수 있는 메뉴도 만들어줘."
“여행 사진 갤러리 페이지를 만들어줘. 위에는 '국내여행', '해외여행', '맛집' 세 개 메뉴를 만들어서 누르면 그 자리로 이동하게 하고, 각 자리에는 작은 사진들을 늘어놓아줘. 그리고 위쪽에 큰 화면 자리를 하나 만들어서, 작은 사진 중 아무거나 누르면 그 사진이 큰 화면에 나타나고 밑에 짧은 설명도 같이 바뀌게 해줘.”
“이 사진들을 갤러리에 넣어줘. 사진은 html 파일이랑 같은 폴더에 둘 거니까, 새 폴더는 만들지 말고 사진 이름만 코드에 적어줘. 그리고 html 파일 이름과 사진 파일 이름 둘 다, 지금까지 받은 파일이랑 안 겹치게 새 번호를 붙여서 줘.”
이 여행 갤러리 페이지에 ‘경비 정산’ 메뉴를 하나 더 추가해줘. 메뉴를 누르면 그 자리로 이동하게 해줘. 그리고 위쪽 메뉴를 눌러서 어느 자리로 이동하든, 그 자리의 제목이 맨 위 고정 메뉴줄과 큰 사진 화면에 가려지지 않고 제목부터 딱 보이는 위치에서 멈추게 해줘. 단, 화면에 실제로 빈 공백을 만들지는 말고, 손으로 스크롤해서 내릴 때는 지금처럼 자연스럽게 이어지되 ‘메뉴를 눌러 이동할 때만’ 제목이 안 가려지게 멈추는 위치를 조절해줘. 모든 메뉴가 똑같이 그렇게 되게 해줘. 정산 기능은 이렇게 만들어줘. 먼저 경비 항목을 여러 줄 적을 수 있게 해줘. 왼쪽에는 항목 이름(예: 숙소, 기름값, 저녁식사), 오른쪽에는 금액을 넣게 하고, ‘항목 추가’ 단추를 누르면 빈 줄이 하나씩 늘어나게 해줘. 금액을 넣으면 맨 아래에 총액이 저절로 합산돼서 보이게 해줘. 그 아래에 어른 수와 아이 수를 넣는 칸을 만들어줘. 그리고 아이의 몫을 어떻게 할지 단추 세 개 중 하나로 고르게 해줘 — ‘다 똑같이 나눠요’, ‘아이는 반만 내요’, ‘아이는 안 내요’ 이렇게. ‘다 똑같이’는 어른 아이 모두 한 명당 같은 금액, ‘아이는 반만’은 아이 한 명이 어른 한 명의 절반, ‘아이는 안 내요’는 어른들만 나눠 내는 거야. ‘정산하기’ 단추를 누르면 어른 한 명당 얼마, 아이 한 명당 얼마씩 내면 되는지 큰 글씨로 보여줘. 딱 나누어떨어지지 않으면 100원 단위로 올려서 계산하고, 총무에게 얼마가 남는지도 알려줘. 사진은 html 파일이랑 같은 폴더에 둘 거니까 새 폴더는 만들지 말고 사진 이름만 그대로 써줘. html 파일 이름은 지금까지 받은 파일이랑 안 겹치게 새 번호를 붙여서 줘.
"핸드폰에서 보니까 맨 위 메뉴 부분이 겹쳐서 깨져. 핸드폰 화면에서도 안 겹치고 잘 보이게 고쳐줘."

이 책의 실습 자료는 위의 「다운로드 (.zip)」 버튼 하나로 받습니다. 압축을 풀면 폴더 다섯 개가 나오고, 각 폴더 안에 코드와 사진과 요청문이 함께 들어 있습니다. index.html을 두 번 누르면 바로 열립니다.
■ 무엇이 들어 있나 압축을 풀면 이런 폴더가 나옵니다. 0_시작파일 책을 시작할 때 씁니다. 여기서 출발합니다. 1_2부까지 2부를 마쳤을 때의 상태 2_3부까지 3부를 마쳤을 때의 상태 3_4부까지 4부를 마쳤을 때의 상태 4_완성본 6부까지 다 마친 최종본 각 폴더 안에 들어 있는 것 index.html 두 번 누르면 브라우저에서 바로 열립니다 style.css script.js images/ 사진. 따로 받거나 옮길 필요가 없습니다 요청문.txt 이 폴더에서 이어서 보낼 요청문 ■ 이렇게 쓰시면 됩니다 1. 0_시작파일 폴더를 복사해 실습용 폴더를 따로 만듭니다. 원본은 손대지 말고 복사본만 고쳐 갑니다. 2. 그 폴더의 요청문.txt 를 엽니다. 3. 실습용 폴더를 통째로 압축해 AI에 첨부하고, 요청문을 위에서부터 하나씩 복사해 보냅니다. 4. 하나 보낼 때마다 책의 「직접 해 보기」로 확인하고 다음으로 갑니다. 어긋나면 책의 「이럴 때는」 상자에 있는 한 줄을 이어서 보내면 됩니다. 5. 중간에 막히거나 크게 망가지면, 그 부까지 끝난 폴더를 복사해 다시 시작합니다. 예를 들어 4부를 하다 막혔다면 2_3부까지 폴더에서 다시 출발합니다. ■ 요청문 21개를 한 파일로 보고 싶다면 압축 안에 요청문_전체.txt 가 들어 있습니다. 책 순서대로 21개가 모여 있어, 폴더별로 나뉜 것이 헷갈릴 때 이 파일 하나만 보셔도 됩니다. ■ 알아 두실 것 같은 요청문을 보내도 AI가 만드는 코드는 조금씩 다르게 나옵니다. 정상입니다. 코드가 글자까지 같을 필요는 없고, 기능이 책과 같게 동작하면 됩니다.

기본적으로 C언어를 다룰 줄 아는 분들을 위해 만들어진 책입니다. 그래서 이 책은 C#을 처음부터 다시 가르치지 않습니다. 변수가 무엇인지, 반복문이 무엇인지는 이미 알고 계실 테니 빠르게 넘어갑니다. 대신 "C에서 이렇게 쓰던 것이 C#에서는 이렇게 바뀐다"만 짚습니다. 알고 있는 문법 위에 그대로 얹어 가는 방식입니다. 그래서 이 책의 예제는 대부분 C 코드와 C# 코드가 나란히 나옵니다. 파란 줄이 그어진 코드가 C언어이고, 보라색 줄이 그어진 코드가 C#입니다. 앞의 것은 이미 아는 것이고, 뒤의 것이 새로 익힐 것입니다. 두 코드 사이에서 달라지는 지점은 파란색 박스에 따로 정리해 두었으니, 시간이 없다면 그 박스만 따라 읽어도 됩니다. 이 책에 특별히 공을 들이는 곳은 6장 클래스입니다. C에는 없던 개념이기 때문입니다. 반대로 포인터는 분량이 적습니다. C#에서는 포인터를 거의 쓰지 않게 되는데, 그것이 왜 그런지, 그러면 C에서 포인터로 하던 일을 C#에서는 무엇으로 대신하는지를 알려드립니다. 그리고 C#을 배우는 분들의 대부분은 유니티(Unity)가 목적입니다. 이 책은 유니티 화면을 다루지는 않지만, 각 문법이 유니티에서 어떤 모습으로 나타나는지를 노란색 박스로 계속 짚어 드립니다. 마지막 부록에서는 지금까지 배운 문법만으로 이루어진 실제 유니티 스크립트를 한 줄씩 읽어 봅니다. 처음 보는 용어가 나온다면 본문에는 자세한 설명이 없을 수 있으니 인터넷으로 검색해 보기 바랍니다. 이 책은 상세한 설명보다 실습을 해보는 것에 초점을 두었습니다. [긴 문장의 실습용 코드는 아래 링크되어 있는 출판사 홈페이지에 있습니다. 코드 실행 과정을 빠르게 확인하고 싶은 분들은 복사해서 사용하시기 바랍니다] https://moesanpublishing.com/books.html
#include <stdio.h>
int main() {
// 여기서 코드를 작성합니다.
return 0;
}
using System;
class Program
{
static void Main()
{
// 여기서 코드를 작성합니다.
}
}
#include <stdio.h>
int main() {
printf("Hello C\n");
return 0;
}
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello C#");
}
}
int a = 10;
int b = 20;
int c = a + b;
printf("%d\n", c);
int a = 10;
int b = 20;
int c = a + b;
Console.WriteLine(c);
int a = 10; // 정수
int b = -20; // 음수
float d = 0.2; // 그냥 통과됩니다
double e = -3.0;
int a = 10; // 정수
int b = -20; // 음수
float d = 0.2f; // f 를 붙여야 합니다
double e = -3.0;
Console.WriteLine(a + b);
Console.WriteLine(d);
Console.WriteLine(e);
int a = 7;
int b = 3;
printf("%d\n", a / b);
printf("%d\n", a % b);
printf("%f\n", (float)a / b);
int a = 7;
int b = 3;
Console.WriteLine(a / b);
Console.WriteLine(a % b);
Console.WriteLine((float)a / b);
int money = 5000;
int apple = 800;
int count = money / apple;
Console.WriteLine("사과를 " + count + "개 살 수 있습니다.");
char grade = 'A';
char name[20] = "홍길동"; // 문자열은 char 배열
printf("%c\n", grade);
printf("%s\n", name);
char grade = 'A';
string name = "홍길동"; // 문자열은 string 하나로
Console.WriteLine(grade);
Console.WriteLine(name);
char a[20] = "Hello";
char b[20];
strcpy(b, a); // 복사
strcat(b, " World"); // 이어 붙이기
if (strcmp(a, "Hello") == 0) printf("같습니다\n");
string a = "Hello";
string b = a; // 복사
b = b + " World"; // 이어 붙이기
if (a == "Hello") Console.WriteLine("같습니다");
int isJumping = 0; // 거짓
isJumping = 1; // 참
if (isJumping) printf("점프 중\n");
bool isJumping = false;
isJumping = true;
if (isJumping) Console.WriteLine("점프 중");
int a = 10;
printf("나는 어제 %d개의 사탕을 먹었습니다.\n", a);
int a = 10;
Console.WriteLine("나는 어제 " + a + "개의 사탕을 먹었습니다.");
Console.WriteLine($"나는 어제 {a}개의 사탕을 먹었습니다.");
float avg = 86.25;
printf("평균: %.2f\n", avg);
float avg = 86.25f;
Console.WriteLine($"평균: {avg:F2}");
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int age;
printf("나이를 입력하세요: ");
scanf("%d", &age);
printf("당신은 %d살입니다.\n", age);
return 0;
}
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine($"당신은 {age}살입니다.");
Console.Write("이름을 입력하세요: ");
string name = Console.ReadLine();
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine($"안녕하세요, {name}님! 당신은 {age}살입니다.");
Console.Write("첫 번째 정수를 입력하세요: ");
int a = int.Parse(Console.ReadLine());
Console.Write("두 번째 정수를 입력하세요: ");
int b = int.Parse(Console.ReadLine());
Console.WriteLine($"합: {a + b}");
Console.WriteLine($"차: {a - b}");
Console.WriteLine($"곱: {a * b}");
Console.WriteLine($"몫: {a / b}");
Console.WriteLine($"나머지: {a % b}");
float f = 3.9;
int i = (int)f; // 3 (소수점 버림)
char c = 'A';
int n = c; // 65 (아스키 값)
float f = 3.9f;
int i = (int)f; // 3 (소수점 버림)
string s = "2021";
int year = int.Parse(s); // 문자열 → 정수
string back = year.ToString(); // 정수 → 문자열
Console.WriteLine($"{i} / {year} / {back}");
#define MAX_HP 100
const int SPEED = 5;
const int MaxHp = 100;
const float Speed = 5f;
Console.WriteLine(MaxHp);
int money = 1000;
int candy = 200;
if (money > candy) {
printf("캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
int money = 1000;
int candy = 200;
if (money > candy)
{
Console.WriteLine("캔디를 살 수 있습니다.");
}
else
{
Console.WriteLine("캔디를 살 수 없습니다.");
}
int money = 5;
int candy = 7;
int point = 2;
if (money > candy) {
printf("1-캔디를 살 수 있습니다.\n");
} else if (money == candy) {
printf("2-캔디를 살 수 있습니다.\n");
} else if (point >= 2) {
printf("3-캔디를 살 수 있습니다.\n");
} else {
printf("캔디를 살 수 없습니다.\n");
}
int money = 5;
int candy = 7;
int point = 2;
if (money > candy)
Console.WriteLine("1-캔디를 살 수 있습니다.");
else if (money == candy)
Console.WriteLine("2-캔디를 살 수 있습니다.");
else if (point >= 2)
Console.WriteLine("3-캔디를 살 수 있습니다.");
else
Console.WriteLine("캔디를 살 수 없습니다.");
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
if (age >= 20)
Console.WriteLine("성인");
else
Console.WriteLine("미성년자");
Console.Write("정수 세 개를 한 줄에 하나씩 입력하세요: ");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
if (a > b && a > c)
Console.WriteLine($"가장 큰 수는 {a}입니다.");
else if (b > a && b > c)
Console.WriteLine($"가장 큰 수는 {b}입니다.");
else
Console.WriteLine($"가장 큰 수는 {c}입니다.");
int score = 3;
switch (score) {
case 1:
printf("C등급입니다.\n");
break;
case 2:
printf("B등급입니다.\n");
break;
case 3:
printf("A등급입니다.\n");
break;
default:
printf("등급을 매길 수 없습니다.\n");
}
int score = 3;
switch (score)
{
case 1:
Console.WriteLine("C등급입니다.");
break;
case 2:
Console.WriteLine("B등급입니다.");
break;
case 3:
Console.WriteLine("A등급입니다.");
break;
default:
Console.WriteLine("등급을 매길 수 없습니다.");
break;
}
string command = "공격";
switch (command)
{
case "공격":
Console.WriteLine("칼을 휘두릅니다.");
break;
case "방어":
Console.WriteLine("방패를 듭니다.");
break;
default:
Console.WriteLine("알 수 없는 명령입니다.");
break;
}
int clear = 0;
while (clear < 5) {
printf("현재까지 게임을 %d번 클리어 했습니다.\n", clear);
clear = clear + 1;
if (clear == 5) {
printf("레벨이 올라갑니다.\n");
}
}
int clear = 0;
while (clear < 5)
{
Console.WriteLine($"현재까지 게임을 {clear}번 클리어 했습니다.");
clear = clear + 1;
if (clear == 5)
{
Console.WriteLine("레벨이 올라갑니다.");
}
}
int cupramen = 4;
while (true)
{
Console.Write("돈을 넣으세요: ");
int money = int.Parse(Console.ReadLine());
if (money == 1500)
{
Console.WriteLine("컵라면을 줍니다.");
cupramen--;
}
else if (money > 1500)
{
Console.WriteLine($"컵라면을 주고, 거스름돈 {money - 1500}원을 돌려 줍니다.");
cupramen--;
}
else
{
Console.WriteLine("돈이 모자랍니다. 돈을 돌려줍니다.");
}
if (cupramen == 0)
{
Console.WriteLine("컵라면이 다 떨어졌습니다.");
break;
}
}
Console.Write("학생수를 입력하시오: ");
int people = int.Parse(Console.ReadLine());
int count = 1;
int sum = 0;
while (count <= people)
{
Console.Write($"{count}번 학생의 점수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
sum += num;
count++;
}
Console.WriteLine($"총합계는 {sum}입니다.");
Console.WriteLine($"평균은 {(float)sum / people:F2}입니다.");
int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
for (int i = 0; i < 5; i++)
{
Console.Write($"{i} ");
}
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= num; i++)
{
sum += i;
}
Console.WriteLine($"합: {sum}");
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", j);
}
printf("\n");
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write($"{j} ");
}
Console.WriteLine();
}
for (int dan = 2; dan <= 5; dan++)
{
Console.WriteLine($"=== {dan}단 ===");
for (int num = 1; num <= 9; num++)
{
Console.WriteLine($"{dan} × {num} = {dan * num}");
}
Console.WriteLine();
}
for (int i = 1; i <= 5; i++)
{
// 공백 출력
for (int j = 1; j <= 5 - i; j++)
{
Console.Write(" ");
}
// 숫자 출력
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write(k);
}
Console.WriteLine();
}
// 크기만 지정
int arr[5];
// 크기와 함께 초기화
int arr2[5] = {1, 2, 3, 4, 5};
// 크기 생략
int arr3[] = {1, 2, 3, 4, 5};
// 크기만 지정 (전부 0으로 채워집니다)
int[] arr = new int[5];
// 크기와 함께 초기화
int[] arr2 = new int[5] { 1, 2, 3, 4, 5 };
// 크기 생략
int[] arr3 = { 1, 2, 3, 4, 5 };
int[] arr = new int[5];
Console.WriteLine(arr[0]);
Console.WriteLine(arr[4]);
int arr[5] = {10, 20, 30, 40, 50};
printf("%d\n", arr[0]);
printf("%d\n", arr[4]);
arr[2] = 100;
// 배열 크기 구하기
int size = sizeof(arr) / sizeof(arr[0]);
int[] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine(arr[0]);
Console.WriteLine(arr[4]);
arr[2] = 100;
// 배열 크기 구하기
int size = arr.Length;
Console.WriteLine($"크기: {size}");
int arr[5] = {1, 4, 8, 9, 13};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
int[] arr = { 1, 4, 8, 9, 13 };
for (int i = 0; i < arr.Length; i++)
{
Console.Write($"{arr[i]} ");
}
int[] arr = { 1, 4, 8, 9, 13 };
foreach (int x in arr)
{
Console.Write($"{x} ");
}
int[] arr = { 34, 67, 43, 89, 55, 3, 45 };
int max = arr[0];
foreach (int x in arr)
{
if (max < x)
{
max = x;
}
}
Console.WriteLine($"가장 큰 수는 {max}입니다.");
int[] arr = { 10, 20, 30, 40, 50 };
int sum = 0;
foreach (int x in arr)
{
sum += x;
}
Console.WriteLine($"합: {sum}");
Console.WriteLine($"평균: {(float)sum / arr.Length:F2}");
using System;
using System.Collections.Generic; // List 를 쓰려면 필요합니다
class Program
{
static void Main()
{
List<string> items = new List<string>();
items.Add("포션"); // 추가
items.Add("검");
items.Add("방패");
Console.WriteLine(items[0]); // 인덱스로 접근
Console.WriteLine(items.Count); // 개수
items.Remove("검"); // 값으로 삭제
Console.WriteLine(items.Count);
foreach (string item in items)
{
Console.Write($"{item} ");
}
}
}
List<string> items = new List<string>();
items.Add("포션");
items.Add("낡은 검");
items.Add("나무 방패");
items.Remove("낡은 검");
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"{i + 1}번 칸: {items[i]}");
}
int arr[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("%d\n", arr[1][2]); // 7
int[,] arr = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
Console.WriteLine(arr[1, 2]); // 7
int[,] arr = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write($"{arr[i, j]} ");
}
Console.WriteLine();
}
int[,] scores = {
{ 85, 90, 78, 92 },
{ 88, 76, 95, 87 },
{ 92, 85, 90, 88 }
};
for (int i = 0; i < scores.GetLength(0); i++)
{
int total = 0;
for (int j = 0; j < scores.GetLength(1); j++)
{
total += scores[i, j];
}
Console.WriteLine($"{i + 1}번 학생 평균: {(float)total / scores.GetLength(1):F2}");
}
char str[] = "Hello";
printf("%d\n", (int)strlen(str));
printf("%c\n", str[0]);
printf("%c\n", str[4]);
string str = "Hello";
Console.WriteLine(str.Length);
Console.WriteLine(str[0]);
Console.WriteLine(str[4]);
// C — string.h 필요
strlen(a); // 길이
strcpy(b, a); // 복사
strcat(a, b); // 이어 붙이기
strcmp(a, b) == 0; // 비교
// C# — 아무것도 포함하지 않아도 됩니다
a.Length; // 길이
string b = a; // 복사
a = a + b; // 이어 붙이기
a == b; // 비교
string a = "Hello World";
Console.WriteLine(a.ToUpper()); // 전부 대문자
Console.WriteLine(a.ToLower()); // 전부 소문자
Console.WriteLine(a.Contains("World")); // 포함하고 있는가
Console.WriteLine(a.Replace("World", "C#")); // 바꾸기
Console.WriteLine(a.Substring(6)); // 6번 자리부터 끝까지
Console.WriteLine(a.Substring(0, 5)); // 0번부터 5글자
Console.WriteLine(a.IndexOf("World")); // 몇 번 자리에 있는가
Console.Write("정수 세 개를 빈칸으로 띄어 입력하세요: ");
string line = Console.ReadLine();
string[] parts = line.Split(' '); // 공백으로 자르기 → 문자열 배열
int a = int.Parse(parts[0]);
int b = int.Parse(parts[1]);
int c = int.Parse(parts[2]);
Console.WriteLine($"합: {a + b + c}");
Console.Write("점수 다섯 개를 빈칸으로 띄어 입력하세요: ");
string[] parts = Console.ReadLine().Split(' ');
int sum = 0;
foreach (string p in parts)
{
sum += int.Parse(p);
}
Console.WriteLine($"총점: {sum}");
Console.WriteLine($"평균: {(float)sum / parts.Length:F2}");
char str[] = "Hello";
int i;
for (i = 0; str[i] != '\0'; i++) {
printf("%c ", str[i]);
}
string str = "Hello";
foreach (char ch in str)
{
Console.Write($"{ch} ");
}
string str = "Hello World";
int count = 0;
foreach (char ch in str)
{
if (ch >= 'A' && ch <= 'Z')
{
count++;
}
}
Console.WriteLine($"대문자 개수: {count}");
string str = "Hello World";
char target = 'l';
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == target)
{
count++;
}
}
Console.WriteLine($"'{target}' 문자가 {count}번 나타납니다.");
char names[3][20] = {"홍길동", "김철수", "이영희"};
int i;
for (i = 0; i < 3; i++) {
printf("%d번: %s\n", i + 1, names[i]);
}
string[] names = { "홍길동", "김철수", "이영희" };
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"{i + 1}번: {names[i]}");
}
string[] names = new string[3];
Console.WriteLine("3명의 이름을 입력하세요.");
for (int i = 0; i < names.Length; i++)
{
Console.Write($"{i + 1}번: ");
names[i] = Console.ReadLine();
}
Console.WriteLine();
Console.WriteLine("입력한 이름:");
foreach (string name in names)
{
Console.WriteLine(name);
}
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
printf("%d\n", result);
return 0;
}
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(10, 20);
Console.WriteLine(result);
}
}
using System;
class Program
{
// 형태 1: 매개변수 없고, 반환값 없음
static void PrintHello()
{
Console.WriteLine("Hello!");
}
// 형태 2: 매개변수 없고, 반환값 있음
static int GetNumber()
{
return 100;
}
// 형태 3: 매개변수 있고, 반환값 없음
static void PrintSum(int a, int b)
{
Console.WriteLine(a + b);
}
// 형태 4: 매개변수 있고, 반환값 있음
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
PrintHello();
Console.WriteLine(GetNumber());
PrintSum(40, 50);
Console.WriteLine(Add(40, 50));
}
}
using System;
class Program
{
static bool IsEven(int num)
{
if (num % 2 == 0)
return true;
else
return false;
}
static void Main()
{
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
if (IsEven(num))
Console.WriteLine("짝수입니다.");
else
Console.WriteLine("홀수입니다.");
}
}
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 3, y = 7;
swap(&x, &y); // 주소를 넘긴다
printf("%d %d\n", x, y);
return 0;
}
using System;
class Program
{
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main()
{
int x = 3, y = 7;
Swap(ref x, ref y); // ref 를 붙인다
Console.WriteLine($"{x} {y}");
}
}
using System;
class Program
{
// 몫과 나머지를 한꺼번에 돌려주고 싶을 때
static void Divide(int a, int b, out int mok, out int namuji)
{
mok = a / b;
namuji = a % b;
}
static void Main()
{
Divide(7, 3, out int m, out int n);
Console.WriteLine($"몫: {m}, 나머지: {n}");
}
}
Console.Write("정수를 입력하세요: ");
string input = Console.ReadLine();
if (int.TryParse(input, out int num))
{
Console.WriteLine($"입력한 값의 두 배는 {num * 2}입니다.");
}
else
{
Console.WriteLine("숫자가 아닙니다.");
}
#include <stdio.h>
void doubleArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
doubleArray(arr, 5); // 크기도 함께 넘긴다
return 0;
}
using System;
class Program
{
static void DoubleArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = arr[i] * 2;
}
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
DoubleArray(arr); // 크기는 넘기지 않는다
foreach (int x in arr)
{
Console.Write($"{x} ");
}
}
}
using System;
class Program
{
static int SumArray(int[] arr)
{
int sum = 0;
foreach (int x in arr)
{
sum += x;
}
return sum;
}
static void Main()
{
int[] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine($"합: {SumArray(arr)}");
}
}
using System;
class Program
{
static float MaxPoint(float[] scores)
{
float max = scores[0];
foreach (float s in scores)
{
if (max < s) max = s;
}
return max;
}
static float MinPoint(float[] scores)
{
float min = scores[0];
foreach (float s in scores)
{
if (min > s) min = s;
}
return min;
}
static float DifPoint(float[] scores)
{
return MaxPoint(scores) - MinPoint(scores);
}
static void Main()
{
float[] points = { 9.5f, 8.8f, 7.0f, 7.9f, 10.0f };
Console.WriteLine(DifPoint(points));
}
}
using System;
class Program
{
static void Count(int a)
{
if (a == 0)
{
return; // 종료 조건
}
Console.Write($"{a} ");
Count(a - 1); // 자기 자신 호출
}
static void Main()
{
Count(5);
}
}
using System;
class Program
{
static int Sum(int n)
{
if (n == 0)
{
return 0; // 종료 조건
}
return n + Sum(n - 1); // n + (n-1까지의 합)
}
static void Main()
{
Console.WriteLine($"1부터 10까지의 합: {Sum(10)}");
}
}
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static float Add(float a, float b) // 이름이 같아도 됩니다
{
return a + b;
}
static int Add(int a, int b, int c) // 개수가 달라도 됩니다
{
return a + b + c;
}
static void Main()
{
Console.WriteLine(Add(10, 20));
Console.WriteLine(Add(1.5f, 2.5f));
Console.WriteLine(Add(10, 20, 30));
}
}
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int score;
};
void introduce(struct Student s) {
printf("%s의 점수: %d\n", s.name, s.score);
}
int main() {
struct Student s1 = {"홍길동", 95};
introduce(s1);
return 0;
}
using System;
class Student
{
public string name; // 데이터
public int score;
public void Introduce() // 그 데이터를 다루는 함수
{
Console.WriteLine($"{name}의 점수: {score}");
}
}
class Program
{
static void Main()
{
Student s1 = new Student();
s1.name = "홍길동";
s1.score = 95;
s1.Introduce();
}
}
Student s1 = new Student();
s1.name = "홍길동";
s1.score = 95;
Student s2 = new Student();
s2.name = "김철수";
s2.score = 45;
s1.Introduce();
s2.Introduce();
class Player
{
public string name; // 밖에서 접근 가능
private int hp; // 클래스 안에서만 접근 가능
}
using System;
class Player
{
public string name;
private int hp = 100; // 밖에서 직접 못 건드립니다
public void TakeDamage(int damage)
{
hp -= damage;
if (hp < 0)
{
hp = 0; // 0 밑으로는 내려가지 않게
}
Console.WriteLine($"{name}의 남은 체력: {hp}");
}
}
class Program
{
static void Main()
{
Player p = new Player();
p.name = "홍길동";
p.TakeDamage(30);
p.TakeDamage(90);
// p.hp = -999; ← 이 줄은 오류가 납니다
}
}
struct Student s1 = {"홍길동", 95};
using System;
class Student
{
public string name;
public int score;
// 생성자 — 클래스와 이름이 같고, 반환형이 없습니다
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
public void Introduce()
{
Console.WriteLine($"{name}의 점수: {score}");
}
}
class Program
{
static void Main()
{
Student s1 = new Student("홍길동", 95);
Student s2 = new Student("김철수", 45);
s1.Introduce();
s2.Introduce();
}
}
class Student
{
public string name;
public int score;
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
public Student(string name) // 점수를 안 줬을 때
{
this.name = name;
this.score = 0;
}
}
int isPass(struct Student s) {
if (s.score >= 60) return 1;
else return 0;
}
// 호출
if (isPass(s1)) printf("%s: 합격\n", s1.name);
using System;
class Student
{
public string name;
public int score;
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
public bool IsPass() // 매개변수가 없습니다
{
return score >= 60;
}
public void PrintResult()
{
if (IsPass()) // 같은 클래스의 메서드는 그냥 부릅니다
Console.WriteLine($"{name}: 합격");
else
Console.WriteLine($"{name}: 불합격");
}
}
class Program
{
static void Main()
{
Student s1 = new Student("홍길동", 95);
Student s2 = new Student("김철수", 45);
s1.PrintResult();
s2.PrintResult();
}
}
using System;
class Student
{
public string name;
public int score;
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
public void PrintResult()
{
if (score >= 60)
Console.WriteLine($"{name}: {score}점 — 합격");
else
Console.WriteLine($"{name}: {score}점 — 불합격");
}
}
class Program
{
static void Main()
{
Student[] students = {
new Student("김철수", 85),
new Student("이영희", 92),
new Student("박민수", 55)
};
int total = 0;
foreach (Student s in students)
{
s.PrintResult();
total += s.score;
}
Console.WriteLine($"전체 평균: {(float)total / students.Length:F1}");
}
}
using System;
class Calculator
{
public static int Add(int a, int b) // static 메서드
{
return a + b;
}
}
class Program
{
static void Main()
{
// 객체를 만들지 않고 클래스 이름으로 바로 부릅니다
Console.WriteLine(Calculator.Add(10, 20));
}
}
using System;
class Monster
{
public static int count = 0; // 모두가 함께 쓰는 값
public string name;
public Monster(string name)
{
this.name = name;
count++; // 태어날 때마다 하나씩
}
}
class Program
{
static void Main()
{
Monster m1 = new Monster("슬라임");
Monster m2 = new Monster("고블린");
Monster m3 = new Monster("드래곤");
Console.WriteLine($"지금까지 태어난 몬스터: {Monster.count}마리");
}
}
using System;
class Player
{
private int hp = 100; // 진짜 값은 감춰 둡니다
public int Hp // 밖에서 쓰는 통로
{
get { return hp; } // 읽을 때
set
{
if (value < 0) // 쓸 때 검사
hp = 0;
else if (value > 100)
hp = 100;
else
hp = value;
}
}
}
class Program
{
static void Main()
{
Player p = new Player();
p.Hp = 70; // 변수처럼 씁니다
Console.WriteLine(p.Hp);
p.Hp = -999; // 걸러집니다
Console.WriteLine(p.Hp);
p.Hp = 500; // 이것도 걸러집니다
Console.WriteLine(p.Hp);
}
}
public int Hp { get; set; } = 100; // 검사 없이 통로만
public string Name { get; private set; } // 밖에서는 읽기만 가능
using System;
class Monster // 부모 클래스
{
public string name;
public int hp;
public void Attack()
{
Console.WriteLine($"{name}이(가) 공격합니다.");
}
}
class Dragon : Monster // Monster 를 상속받습니다
{
public void Fly() // 드래곤만의 기능을 추가
{
Console.WriteLine($"{name}이(가) 날아오릅니다.");
}
}
class Program
{
static void Main()
{
Dragon d = new Dragon();
d.name = "붉은용"; // 부모에게서 물려받은 것
d.hp = 500;
d.Attack(); // 부모의 메서드
d.Fly(); // 자기 메서드
}
}
using System;
class Monster
{
public string name;
public int hp;
public Monster(string name, int hp)
{
this.name = name;
this.hp = hp;
}
}
class Dragon : Monster
{
public int firePower;
public Dragon(string name, int hp, int firePower) : base(name, hp)
{
this.firePower = firePower;
}
}
class Program
{
static void Main()
{
Dragon d = new Dragon("붉은용", 500, 99);
Console.WriteLine($"{d.name} 체력 {d.hp} 화력 {d.firePower}");
}
}
using System;
class Monster
{
public string name;
public Monster(string name)
{
this.name = name;
}
public virtual void Attack() // 고쳐 써도 좋다
{
Console.WriteLine($"{name}이(가) 몸통박치기를 합니다.");
}
}
class Dragon : Monster
{
public Dragon(string name) : base(name) { }
public override void Attack() // 고쳐 쓰겠다
{
Console.WriteLine($"{name}이(가) 불을 뿜습니다!");
}
}
class Slime : Monster
{
public Slime(string name) : base(name) { }
// Attack 을 고치지 않았으므로 부모 것을 그대로 씁니다
}
class Program
{
static void Main()
{
Monster[] monsters = {
new Slime("슬라임"),
new Dragon("붉은용")
};
foreach (Monster m in monsters)
{
m.Attack();
}
}
}
public override void Attack()
{
base.Attack(); // 부모의 공격을 먼저 실행
Console.WriteLine("그리고 꼬리로 한 번 더 칩니다.");
}
using System;
class Calculator
{
private int a;
private int b;
public Calculator(int a, int b)
{
this.a = a;
this.b = b;
}
public int Plus() { return a + b; }
public int Minus() { return a - b; }
public int Mul() { return a * b; }
public float Div()
{
if (b == 0)
{
Console.WriteLine("0으로 나눌 수 없습니다.");
return 0;
}
return (float)a / b;
}
}
class Program
{
static void Main()
{
Calculator c = new Calculator(10, 20);
Console.WriteLine(c.Plus());
Console.WriteLine(c.Minus());
Console.WriteLine(c.Mul());
Console.WriteLine(c.Div());
}
}
enum PlayerState { IDLE, RUN, JUMP };
enum PlayerState state = IDLE;
if (state == IDLE) {
printf("대기 중\n");
}
enum PlayerState { Idle, Run, Jump }
PlayerState state = PlayerState.Idle;
if (state == PlayerState.Idle)
{
Console.WriteLine("대기 중");
}
enum Grade { A = 90, B = 80, C = 70 }
Grade g = Grade.B;
Console.WriteLine(g); // 이름이 그대로 나옵니다
Console.WriteLine((int)g); // 숫자로 보고 싶으면 형변환
using System;
enum PlayerState { Idle, Run, Jump }
class Program
{
static void Main()
{
PlayerState state = PlayerState.Run;
switch (state)
{
case PlayerState.Idle:
Console.WriteLine("가만히 서 있습니다.");
break;
case PlayerState.Run:
Console.WriteLine("달립니다.");
break;
case PlayerState.Jump:
Console.WriteLine("점프합니다.");
break;
}
}
}
using System;
struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public void Print()
{
Console.WriteLine($"({x}, {y})");
}
}
class Program
{
static void Main()
{
Point p = new Point(10, 20);
p.Print();
}
}
using System;
struct PointS { public int x; } // 구조체 — 값 형식
class PointC { public int x; } // 클래스 — 참조 형식
class Program
{
static void Main()
{
PointS s1 = new PointS();
s1.x = 10;
PointS s2 = s1; // 통째로 복사됩니다
s2.x = 99;
PointC c1 = new PointC();
c1.x = 10;
PointC c2 = c1; // 같은 것을 함께 가리킵니다
c2.x = 99;
Console.WriteLine($"구조체 s1.x = {s1.x}");
Console.WriteLine($"클래스 c1.x = {c1.x}");
}
}
using System;
enum Rank { Normal, Elite, Boss }
class Monster
{
public string name;
public Rank rank;
public Monster(string name, Rank rank)
{
this.name = name;
this.rank = rank;
}
public void GiveReward()
{
switch (rank)
{
case Rank.Normal:
Console.WriteLine($"{name} 처치 — 골드 10");
break;
case Rank.Elite:
Console.WriteLine($"{name} 처치 — 골드 100");
break;
case Rank.Boss:
Console.WriteLine($"{name} 처치 — 골드 1000과 전설 아이템");
break;
}
}
}
class Program
{
static void Main()
{
Monster[] monsters = {
new Monster("슬라임", Rank.Normal),
new Monster("오크 대장", Rank.Elite),
new Monster("붉은용", Rank.Boss)
};
foreach (Monster m in monsters)
{
m.GiveReward();
}
}
}
using UnityEngine;
using System.Collections.Generic;
public enum PlayerState
{
Idle,
Run,
Jump
}
public class Player : MonoBehaviour
{
public int Hp { get; set; } = 100;
public float speed = 5f;
private PlayerState state = PlayerState.Idle;
private List<string> items = new List<string>();
void Start()
{
items.Add("포션");
Debug.Log($"게임 시작! HP: {Hp}");
}
void Update()
{
if (Hp <= 0)
{
state = PlayerState.Idle;
Debug.Log("플레이어가 쓰러졌습니다.");
}
switch (state)
{
case PlayerState.Run:
transform.Translate(Vector3.forward * speed * Time.deltaTime);
break;
}
}
void TakeDamage(int damage)
{
Hp -= damage;
}
}

※ 이 책은 집필 과정에서 생성형 AI 도구의 도움을 받았습니다. 파이썬을 조금 다뤄 본 사람이 C#을 배우려 할 때, 입문서를 처음부터 다시 읽을 필요는 없습니다. 이미 아는 파이썬을 발판으로 삼으면, C#에서 새로 익혀야 할 것만 골라 빠르게 배울 수 있습니다. 이 책은 파이썬 코드와 C# 코드를 나란히 놓고, 무엇이 같고 무엇이 달라지는지 짚어 갑니다. 변수와 자료형, 제어문, 리스트와 딕셔너리, 문자열, 함수, 클래스와 객체, 값 형식과 참조 형식까지 차례로 따라가며, 직접 코드를 입력하고 실행하면서 익히도록 구성했습니다. C#을 배우는 사람 대부분이 유니티를 목표로 하는 만큼, 각 문법이 유니티 스크립트에서 어떻게 쓰이는지도 곳곳에서 짚고, 부록에서는 AI가 만드는 유니티 코드에 자주 나오는 표기와 실전 스크립트를 예제로 설명합니다. 파이썬을 알고 C#으로 넘어가려는 분, 유니티를 시작하기 전에 C#을 빠르게 익히고 싶은 분께 알맞은 책입니다.
print('hello')
using System;
class Program
{
static void Main()
{
Console.WriteLine("hello");
}
}
a = 10
b = 20
c = a + b
print(c)
int a = 10;
int b = 20;
int c = a + b;
Console.WriteLine(c);
a = 10
b = -20
d = 0.2
e = -3.0
int a = 10;
int b = -20;
float d = 0.2f; // 실수에는 f 를 붙입니다
double e = -3.0;
a = 7
b = 3
print(a / b) # 나누기
print(a // b) # 몫
print(a % b) # 나머지
int a = 7;
int b = 3;
Console.WriteLine((float)a / b); // 파이썬의 a / b — 실수로 보려면 형변환
Console.WriteLine(a / b); // 파이썬의 a // b — 정수끼리는 몫만 나옵니다
Console.WriteLine(a % b); // 파이썬의 a % b — 나머지
int money = 5000;
int apple = 800;
int count = money / apple;
Console.WriteLine($"사과를 {count}개 살 수 있습니다.");
a = 'Hello'
b = "World"
c = a + b # 이어 붙이기
d = a * 3 # 반복
string a = "Hello";
string b = "World";
string c = a + b; // 이어 붙이기 — 그대로 됩니다
// (a * 3)에 해당하는 문법은 C#에 없습니다
string a = "Hello";
string b = "Hello";
if (a == b) Console.WriteLine("같습니다");
is_jumping = False
is_jumping = True
bool isJumping = false;
isJumping = true;
a = 10
print(f"나는 어제 {a}개의 사탕을 먹었습니다.")
int a = 10;
Console.WriteLine($"나는 어제 {a}개의 사탕을 먹었습니다.");
int a = 10, b = 20;
Console.WriteLine($"합은 {a + b}입니다.");
age = int(input('나이를 입력하세요: '))
print(f'당신은 {age}살입니다.')
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
Console.WriteLine($"당신은 {age}살입니다.");
Console.Write("나이를 입력하세요: ");
if (int.TryParse(Console.ReadLine(), out int age))
{
Console.WriteLine($"당신은 {age}살입니다.");
}
else
{
Console.WriteLine("숫자가 아닙니다.");
}
Console.Write("첫 번째 정수: ");
int a = int.Parse(Console.ReadLine());
Console.Write("두 번째 정수: ");
int b = int.Parse(Console.ReadLine());
Console.WriteLine($"합: {a + b}");
Console.WriteLine($"차: {a - b}");
Console.Write("정수 세 개를 한 줄씩 입력하세요: ");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
if (a >= b && a >= c)
Console.WriteLine($"가장 큰 수는 {a}입니다.");
else if (b >= a && b >= c)
Console.WriteLine($"가장 큰 수는 {b}입니다.");
else
Console.WriteLine($"가장 큰 수는 {c}입니다.");
Console.Write("화씨 온도를 입력하세요: ");
float f = float.Parse(Console.ReadLine());
float c = (f - 32) * 5 / 9;
Console.WriteLine($"섭씨 온도는 {c:F1}도입니다.");
MAX_HP = 100 # 관례일 뿐, 실제로는 바꿀 수 있습니다
MAX_HP = 200 # 아무 문제 없이 바뀝니다
const int MaxHp = 100;
// MaxHp = 200; ← 이 줄은 컴파일 오류가 납니다
money = 1000
candy = 200
if money > candy:
print('캔디를 살 수 있습니다.')
else:
print('캔디를 살 수 없습니다.')
int money = 1000;
int candy = 200;
if (money > candy)
{
Console.WriteLine("캔디를 살 수 있습니다.");
}
else
{
Console.WriteLine("캔디를 살 수 없습니다.");
}
if money < candy or point > 7:
if (money < candy || point > 7)
Console.Write("나이를 입력하세요: ");
int age = int.Parse(Console.ReadLine());
if (age >= 20)
Console.WriteLine("성인");
else
Console.WriteLine("미성년자");
score = 2
match score:
case 1:
print('C등급입니다.')
case 2:
print('B등급입니다.')
case _:
print('등급을 매길 수 없습니다.')
int score = 2;
switch (score)
{
case 1:
Console.WriteLine("C등급입니다.");
break;
case 2:
Console.WriteLine("B등급입니다.");
break;
default:
Console.WriteLine("등급을 매길 수 없습니다.");
break;
}
clear = 0
while clear < 5:
print(f'게임을 {clear}번 클리어했습니다.')
clear += 1
int clear = 0;
while (clear < 5)
{
Console.WriteLine($"게임을 {clear}번 클리어했습니다.");
clear++;
}
Console.Write("학생 수를 입력하시오: ");
int people = int.Parse(Console.ReadLine());
int count = 1;
int sum = 0;
while (count <= people)
{
Console.Write($"{count}번 학생의 점수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
sum += num;
count++;
}
Console.WriteLine($"총합계는 {sum}입니다.");
Console.WriteLine($"평균은 {(float)sum / people:F2}입니다.");
for i in range(5):
print(i, end=' ')
for (int i = 0; i < 5; i++)
{
Console.Write($"{i} ");
}
for (초기값; 조건; 증가값)
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= num; i++)
{
sum += i;
}
Console.WriteLine($"합: {sum}");
for dan in range(2, 6):
print(f'=== {dan}단 ===')
for num in range(1, 10):
print(f'{dan} x {num} = {dan*num}')
for (int dan = 2; dan <= 5; dan++)
{
Console.WriteLine($"=== {dan}단 ===");
for (int num = 1; num <= 9; num++)
{
Console.WriteLine($"{dan} x {num} = {dan * num}");
}
}
for (int i = 1; i <= 5; i++)
{
// 공백 출력
for (int j = 1; j <= 5 - i; j++)
{
Console.Write(" ");
}
// 숫자 출력
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write(k);
}
Console.WriteLine();
}
Console.Write("메뉴를 선택하세요 (1-3): ");
int menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
Console.WriteLine("햄버거를 선택하셨습니다.");
break;
case 2:
Console.WriteLine("피자를 선택하셨습니다.");
break;
case 3:
Console.WriteLine("치킨을 선택하셨습니다.");
break;
default:
Console.WriteLine("잘못된 선택입니다.");
break;
}
a = [1, 4, 8, 9, 13]
print(a[0])
print(a[2])
a.append(20)
using System.Collections.Generic; // 파일 맨 위
List<int> a = new List<int> { 1, 4, 8, 9, 13 };
Console.WriteLine(a[0]);
Console.WriteLine(a[2]);
a.Add(20);
a = ['apple', 2021, 'Z', 10, 90, 'yellow']
if 'Z' in a:
print('Z가 들어 있으므로 실행됩니다.')
List<object> a = new List<object> { "apple", 2021, "Z", 10, 90, "yellow" };
if (a.Contains("Z"))
{
Console.WriteLine("Z가 들어 있으므로 실행됩니다.");
}
items = []
items.append('포션')
items.append('검')
items.remove('검')
print(len(items))
List<string> items = new List<string>();
items.Add("포션");
items.Add("검");
items.Remove("검");
Console.WriteLine(items.Count);
int[ ] arr = { 10, 20, 30, 40, 50 };
Console.WriteLine(arr[0]);
Console.WriteLine(arr.Length); // len( )에 해당
int[,] scores = {
{ 85, 90, 78, 92 },
{ 88, 76, 95, 87 },
{ 92, 85, 90, 88 }
};
Console.WriteLine(scores[1, 2]); // 2번째 행, 3번째 열
a = [34, 67, 43, 89, 55, 3, 45]
z = a[0]
for b in a:
if z < b:
z = b
print(z)
List<int> a = new List<int> { 34, 67, 43, 89, 55, 3, 45 };
int z = a[0];
foreach (int b in a)
{
if (z < b)
{
z = b;
}
}
Console.WriteLine(z);
List<int> a = new List<int> { 34, 67, 43, 89, 55, 3, 45 };
a.Sort();
Console.WriteLine(string.Join(" ", a)); // 3 34 43 45 55 67 89
a = [12, 13, 14, 15, 16, 17]
for b in a:
if b % 2 == 0:
print(b, end=' ')
a = [12, 13, 14, 15, 16, 17]
for b in range(len(a)):
if a[b] % 2 == 0:
print(a[b], end=' ')
List<int> a = new List<int> { 12, 13, 14, 15, 16, 17 };
// 방법 1: foreach — 값을 직접 꺼냅니다
foreach (int b in a)
{
if (b % 2 == 0)
{
Console.Write($"{b} ");
}
}
Console.WriteLine();
// 방법 2: 인덱스 — 번호를 셉니다
for (int b = 0; b < a.Count; b++)
{
if (a[b] % 2 == 0)
{
Console.Write($"{a[b]} ");
}
}
a = [[1, 2], [3, 4, 300, 400], [5, 6]]
for b in range(len(a)):
for c in range(len(a[b])):
print(a[b][c], end=' ')
using System.Collections.Generic; // 파일 맨 위
List<List<int>> a = new List<List<int>>
{
new List<int> { 1, 2 },
new List<int> { 3, 4, 300, 400 },
new List<int> { 5, 6 }
};
for (int b = 0; b < a.Count; b++)
{
for (int c = 0; c < a[b].Count; c++)
{
Console.Write($"{a[b][c]} ");
}
}
a = {'school': 'daehan', 'grade': 2}
print(a['school'])
a['year'] = 2021
using System.Collections.Generic; // 파일 맨 위
Dictionary<string, object> a = new Dictionary<string, object>
{
{ "school", "daehan" },
{ "grade", 2 }
};
Console.WriteLine(a["school"]);
a["year"] = 2021;
for key, val in a.items():
print(key, val)
// 위에서 만든 딕셔너리 a 를 이어서 씁니다
foreach (var pair in a)
{
Console.WriteLine($"{pair.Key} {pair.Value}");
}
List<int> a = new List<int> { 10, 20, 30, 40, 50 };
List<int> part = a.GetRange(1, 3); // a[1:4] 에 해당
using System.Collections.Generic; // 파일 맨 위
Dictionary<string, int> students = new Dictionary<string, int>
{
{ "kim", 88 },
{ "lee", 75 },
{ "park", 92 }
};
int total = 0;
foreach (int score in students.Values)
{
total += score;
}
Console.WriteLine($"평균: {(float)total / students.Count:F1}");
foreach (var pair in students)
{
if (pair.Value >= 90)
{
Console.WriteLine($"{pair.Key}: {pair.Value}점");
}
}
a = 'Hello World'
print(a.upper())
print(a.lower())
print(len(a))
print(a.replace('World', 'C#'))
string a = "Hello World";
Console.WriteLine(a.ToUpper());
Console.WriteLine(a.ToLower());
Console.WriteLine(a.Length);
Console.WriteLine(a.Replace("World", "C#"));
a = 'Hello World'
print(a[6:]) # 슬라이싱
parts = a.split(' ') # 나누기
string a = "Hello World";
Console.WriteLine(a.Substring(6)); // 6번 자리부터 끝까지
string[] parts = a.Split(' '); // 나누기
string[] parts = Console.ReadLine().Split(' ');
int sum = 0;
foreach (string p in parts)
{
sum += int.Parse(p);
}
Console.WriteLine($"평균: {(float)sum / parts.Length:F2}");
for ch in 'Hello':
print(ch, end=' ')
foreach (char ch in "Hello")
{
Console.Write($"{ch} ");
}
string a = "Hello World";
char target = 'l';
int count = 0;
foreach (char ch in a)
{
if (ch == target)
{
count++;
}
}
Console.WriteLine($"'{target}' 문자가 {count}번 나타납니다.");
a = 'Hello'
print(a[::-1])
string a = "Hello";
char[] chars = a.ToCharArray(); // 문자열을 문자 배열로
Array.Reverse(chars); // 배열을 뒤집고
string reversed = new string(chars); // 다시 문자열로
Console.WriteLine(reversed);
def add(a, b):
return a + b
result = add(10, 20)
print(result)
using System;
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static void Main()
{
int result = Add(10, 20);
Console.WriteLine(result);
}
}
def greet(name='익명'):
print(f'안녕, {name}')
greet()
greet('홍길동')
static void Greet(string name = "익명") // Main 바깥
{
Console.WriteLine($"안녕, {name}");
}
Greet();
Greet("홍길동");
static int Add(int a, int b) { return a + b; } // Main 바깥
static float Add(float a, float b) { return a + b; } // Main 바깥
Console.WriteLine(Add(1, 2)); // 정수용이 불립니다
Console.WriteLine(Add(1.5f, 2.5f)); // 실수용이 불립니다
def calc(a, b):
return a + b, a * b, a - b
print(calc(4, 6))
static (int, int, int) Calc(int a, int b) // Main 바깥
{
return (a + b, a * b, a - b);
}
var result = Calc(4, 6);
Console.WriteLine($"{result.Item1}, {result.Item2}, {result.Item3}");
string input = "123";
if (int.TryParse(input, out int number))
{
Console.WriteLine(number + 1); // 124
}
using System;
class Program
{
static bool IsEven(int num)
{
return num % 2 == 0;
}
static void Main()
{
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
if (IsEven(num))
Console.WriteLine("짝수입니다.");
else
Console.WriteLine("홀수입니다.");
}
}
def change(a):
a = 99 # 함수 안에서만 바뀝니다
x = 10
change(x)
print(x) # 10 — 안 바뀝니다
def add_item(lst):
lst.append(99) # 원본 리스트가 바뀝니다
a = [1, 2, 3]
add_item(a)
print(a) # [1, 2, 3, 99] — 바뀝니다
// class Program 안에 넣고, 원래 있던 Main( )은 지웁니다
static void Change(int a)
{
a = 99; // 함수 안에서만 바뀝니다
}
static void AddItem(List<int> lst)
{
lst.Add(99); // 원본 리스트가 바뀝니다
}
static void Main()
{
int x = 10;
Change(x);
Console.WriteLine(x); // 10 — 안 바뀝니다
List<int> a = new List<int> { 1, 2, 3 };
AddItem(a);
Console.WriteLine(string.Join(",", a)); // 1,2,3,99 — 바뀝니다
}
using System;
using System.Collections.Generic;
class Program
{
static int PeopleNumber(int max, List<int> people)
{
int answer = 0;
int total = 0;
for (int i = 0; i < people.Count; i++)
{
if (total + people[i] > max) // 이 사람까지 태우면 넘는가?
{
break;
}
total += people[i];
answer += 1;
}
return answer;
}
static void Main()
{
int maxWeight = 300;
List<int> peopleWeights = new List<int> { 65, 77, 80, 45, 90, 110, 72, 88, 41, 99 };
Console.WriteLine(PeopleNumber(maxWeight, peopleWeights));
}
}
try:
num = int(input('정수를 입력하세요: '))
print(f'입력한 값: {num}')
except ValueError:
print('숫자가 아닙니다.')
try
{
Console.Write("정수를 입력하세요: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine($"입력한 값: {num}");
}
catch (FormatException)
{
Console.WriteLine("숫자가 아닙니다.");
}
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def introduce(self):
print(f'{self.name}의 점수: {self.score}')
s1 = Student('홍길동', 95)
s1.introduce()
using System;
class Student
{
public string name = "";
public int score = 0;
public void Introduce()
{
Console.WriteLine($"{name}의 점수: {score}");
}
}
class Program
{
static void Main()
{
Student s1 = new Student();
s1.name = "홍길동";
s1.score = 95;
s1.Introduce();
}
}
using System;
class Student
{
public string name;
public int score;
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
public void Introduce()
{
Console.WriteLine($"{name}의 점수: {score}");
}
}
class Program
{
static void Main()
{
Student s1 = new Student("홍길동", 95);
s1.Introduce();
}
}
class Player:
def __init__(self):
self._hp = 100 # 관례일 뿐, 실제로는 접근 가능
def take_damage(self, damage):
self._hp -= damage
if self._hp < 0:
self._hp = 0
p = Player()
p._hp = -999 # 문법적으로 막을 방법이 없습니다
class Player // Program 바깥
{
private int hp = 100; // 클래스 밖에서 접근하면 오류가 납니다
public void TakeDamage(int damage)
{
hp -= damage;
if (hp < 0) hp = 0;
}
}
// p.hp = -999; ← 이 줄은 컴파일 오류입니다
class Student // Program 바깥
{
public static int count = 0; // 클래스에 하나만 있습니다
public string name; // 객체마다 따로 생깁니다
public Student(string name)
{
this.name = name;
count++; // 만들어질 때마다 1씩
}
}
Student s1 = new Student("홍길동");
Student s2 = new Student("김철수");
Console.WriteLine(Student.count); // 객체가 아니라 클래스 이름으로
class Monster:
def __init__(self, name):
self.name = name
def attack(self):
print(f'{self.name}이(가) 몸통박치기를 합니다.')
class Dragon(Monster):
def attack(self): # 오버라이딩
print(f'{self.name}이(가) 불을 뿜습니다!')
monsters = [Monster('슬라임'), Dragon('붉은용')]
for m in monsters:
m.attack()
using System;
using System.Collections.Generic;
class Monster
{
public string name;
public Monster(string name) { this.name = name; }
public virtual void Attack()
{
Console.WriteLine($"{name}이(가) 몸통박치기를 합니다.");
}
}
class Dragon : Monster
{
public Dragon(string name) : base(name) { }
public override void Attack() // 오버라이딩
{
Console.WriteLine($"{name}이(가) 불을 뿜습니다!");
}
}
class Program
{
static void Main()
{
List<Monster> monsters = new List<Monster>
{
new Monster("슬라임"),
new Dragon("붉은용")
};
foreach (Monster m in monsters)
{
m.Attack();
}
}
}
using System;
class Calculator
{
private int one, two;
public Calculator(int one, int two)
{
this.one = one;
this.two = two;
}
public int Plus() { return one + two; }
public int Minus() { return one - two; }
public int Multiply() { return one * two; }
public float Division() { return (float)one / two; }
}
class Program
{
static void Main()
{
Calculator a = new Calculator(10, 20);
Console.WriteLine(a.Plus());
Console.WriteLine(a.Minus());
Console.WriteLine(a.Multiply());
Console.WriteLine(a.Division());
}
}
class Point:
def __init__(self, score):
self.list_score = score
def final_point(self):
total = sum(self.list_score) - max(self.list_score) - min(self.list_score)
result = total / (len(self.list_score) - 2)
return result
swimming = Point([35, 48, 50, 41, 43])
print(swimming.final_point())
using System;
using System.Collections.Generic;
using System.Linq;
class Point
{
private List<int> listScore;
public Point(List<int> score)
{
listScore = score;
}
public float FinalPoint()
{
int total = listScore.Sum() - listScore.Max() - listScore.Min();
return (float)total / (listScore.Count - 2);
}
}
class Program
{
static void Main()
{
Point swimming = new Point(new List<int> { 35, 48, 50, 41, 43 });
Console.WriteLine(swimming.FinalPoint());
}
}
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [
Student('김철수', 85),
Student('이영희', 92),
Student('박민수', 78),
]
for s in students:
print(f'{s.name}: {s.score}점')
using System;
using System.Collections.Generic;
class Student
{
public string name;
public int score;
public Student(string name, int score)
{
this.name = name;
this.score = score;
}
}
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student("김철수", 85),
new Student("이영희", 92),
new Student("박민수", 78)
};
int total = 0;
foreach (Student s in students)
{
Console.WriteLine($"{s.name}: {s.score}점");
total += s.score;
}
Console.WriteLine($"전체 평균: {(float)total / students.Count:F1}");
}
}
struct PointS { public int x; } // 값 형식 (Program 바깥)
class PointC { public int x; } // 참조 형식 (Program 바깥)
PointS s1 = new PointS(); s1.x = 10;
PointS s2 = s1; // 통째로 복사됩니다
s2.x = 99;
PointC c1 = new PointC(); c1.x = 10;
PointC c2 = c1; // 같은 것을 함께 가리킵니다
c2.x = 99;
Console.WriteLine(s1.x); // 10 — 안 바뀝니다
Console.WriteLine(c1.x); // 99 — 바뀝니다
player = None
print(player) # None
if player is None:
print('아직 만들어지지 않았습니다.')
// 6장의 Student 클래스가 있어야 합니다 (Program 바깥)
Student player = null;
Console.WriteLine(player); // (아무것도 출력되지 않습니다)
if (player == null)
{
Console.WriteLine("아직 만들어지지 않았습니다.");
}
int? score = null; // int 뒤에 ? 를 붙이면 null을 허용합니다
if (score == null)
{
Console.WriteLine("아직 점수가 없습니다.");
}
// 6장의 Student 클래스가 있어야 합니다 (Program 바깥)
Student player = null;
Console.WriteLine(player?.name); // player가 null이면 아무 것도 하지 않고 null을 돌려줍니다
// 유니티 코드입니다
transform.position.x = 5f; // 오류가 납니다
Vector3 pos = transform.position; // 복사본을 꺼내서
pos.x = 5f; // 복사본을 고치고
transform.position = pos; // 통째로 다시 넣습니다
from enum import Enum
class PlayerState(Enum):
IDLE = 0
RUN = 1
JUMP = 2
state = PlayerState.IDLE
enum PlayerState { Idle, Run, Jump } // Program 바깥
PlayerState state = PlayerState.Idle;
public int Hp { get; private set; } = 100;
[SerializeField] private float speed = 5f;
Rigidbody rb = GetComponent<Rigidbody>();
int Double(int x) => x * 2;
button.onClick.AddListener(() => Jump());
if (Physics.Raycast(ray, out RaycastHit hit))
{
Debug.Log(hit.collider.name);
}
IEnumerator Blink()
{
Debug.Log("사라집니다");
yield return new WaitForSeconds(2f); // 2초 기다렸다가
Debug.Log("다시 나타납니다"); // 이어서 실행합니다
}
void Start()
{
StartCoroutine(Blink());
}
using UnityEngine;
using System.Collections.Generic;
public enum PlayerState { Idle, Run, Dead }
public class Player : MonoBehaviour
{
public int Hp { get; private set; } = 100;
[SerializeField] private float speed = 5f;
private PlayerState state = PlayerState.Idle;
private List<string> items = new List<string>();
void Start()
{
items.Add("포션");
Debug.Log($"게임 시작! HP: {Hp}");
}
void Update()
{
if (state == PlayerState.Dead) return;
if (Input.GetKey(KeyCode.W))
state = PlayerState.Run;
else
state = PlayerState.Idle;
if (Input.GetKeyDown(KeyCode.Space))
TakeDamage(30); // 시험용: 스페이스 키를 누르면 데미지
switch (state)
{
case PlayerState.Run:
transform.Translate(Vector3.forward * speed * Time.deltaTime);
break;
case PlayerState.Idle:
break;
}
}
void TakeDamage(int damage)
{
Hp -= damage;
Debug.Log($"HP: {Hp}");
if (Hp <= 0)
{
state = PlayerState.Dead;
Debug.Log("쓰러졌습니다.");
}
}
}