전자책 위주로 출간하고 있으며, 현재도 새로운 책을 준비 중입니다.
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,45]
z=a[0]
b=0
while b<len(a):
if z>a[b]:
z=a[b]
b+=1
print(z)
student=int(input('학생수를 입력하시오: '))
count=1
sum=0
while count<=student:
num = int(input(f"{count}번 학생의 점수를 입력하세요: "))
sum+=num
count+=1
print(f"총합계는 {sum}입니다.")
print(f"평균은 {sum/student}입니다.")
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,"있다")
def num():
a=10
b=20
print(a+b)
num()
def num():
a=10
b=20
return a+b
def num(j, k ):
print(j+k)
x=40
y=50
num(x, y)
def num(j, k ):
return j+k
def add(a , b):
return a+b, a*b, a-b
def add(a,b):
return a +b
return a*b
def add(x , y):
z=x+y
return z
def people_number(max, people):
answer = 0
total = 0
for i in range(len(people)):
total += people[i]
answer += 1
if total > max:
break
return answer - 1
def max_point(scores):
answer = scores[0]
for sc in scores:
if answer<sc:
answer = sc
return answer
def a():
print('hi')
a()
a()
def count(a):
if a==0:
return
print(a, end=' ')
a-=1
count(a)
def count(a):
if a==0:
return
a-=1
count(a)
print(a, end=' ')
def sum(a):
if a == 0:
return 0
return a+sum(a-1)
def multi(a):
if a == 1:
return 1
return a*multi(a-1)
class Game:
name="king"
weapon="thunder"
hp=999
class Game:
name="king"
weapon="thunder"
hp=999
class Game:
name="king"
weapon="thunder"
hp=999
class Game:
def meet(self):
print('hi')
class Game:
def meet(self):
print('hi')
class Game:
korea='안녕'
def meet(self):
print(self.korea)
class Game:
korea='안녕'
def meet(self):
print(korea)
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
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
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
class Game:
def user(self):
print("게임을 시작합니다")
class Player(Game):
def person1(self):
print("케릭터를 고르세요")
class Game:
def __init__(self):
print("게임을 시작합니다")
self.hi="안녕!"
class Game_name:
def hi(self):
print("안녕")
class Game_name:
def hi(self):
print("안녕")
#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("안녕하세요, %s님! 당신은 %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 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", 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;
}
#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;
}
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)}')
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", 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)
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;
}

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;
}
}