💖 星野アイ (◍•ᴗ•◍)♡ ✧*。
-
Day4 : Deep Learning
📌 Deep Learning란?
퍼셉트론(Perceptron)은 생물학적 뉴런을 수학적으로 모델링한 인공 뉴런 모델로,…
🔧 구조 (Perceptron Structure)
입력(x) → 가중치(w) → 가중합(∑) → 활성화 함수(f) → 출력(y)
🛠️ 작업할 디렉토리 생성 및 환경 설정
# 1. 작업 디렉토리 생성
mkdir F_MNIST # 디렉토리 이름: F_MNIST
cd F_MNIST # 해당 디렉토리로 이동
# 2. 가상 환경 생성 및 활성화
python3 -m venv .fmnist # 가상 환경 생성 (폴더 이름: .fmnist)
source .fmnist/bin/activate # 가상 환경 활성화
# 3. 패키지 설치
pip install -U pip # pip 최신 버전으로 업그레이드
pip install tensorflow # TensorFlow (딥러닝 프레임워크)
pip install matplotlib # Matplotlib (시각화 라이브러리)
pip install PyQt5 # PyQt5 (Matplotlib GUI 백엔드용)
pip install scikit_learn # scikit-learn (머신러닝 및 평가 도구)
# 4. Qt GUI 백엔드 설정 (Wayland 환경에서 필수)
export QT_QPA_PLATFORM=wayland # Qt GUI를 Wayland에서 정상 동작하게 설정
👨💻 실습
💡 Code : Fashion MNIST
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# dataset load
fashion_mnist = keras.datasets.fashion_mnist
# spilt data (train / test)
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
matplotlib.use('Qt5Agg')
NUM=20
plt.figure(figsize=(15,15))
plt.subplots_adjust(hspace=1)
for idx in range(NUM):
sp = plt.subplot(5,5,idx+1)
plt.imshow(train_images[idx])
plt.title(f'{class_names[train_labels[idx]]}')
plt.show()
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
# 간단한 이미지 전처리 (for ANN)
train_images = train_images / 255.0
test_images = test_images / 255.0
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.figure(figsize=(10,8))
for i in range(20):
plt.subplot(4,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
model = keras.Sequential ([
keras.layers.Flatten(input_shape=(28,28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax'),
])
model.summary()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=20)
predictions = model.predict(test_images)
predictions[0]
np.argmax(predictions[0])
test_labels[0]
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()
from sklearn.metrics import accuracy_score
print('accuracy score : ', accuracy_score(tf.math.argmax(predictions, -1), test_labels))
aaaaaa
-
Day3 : Perceptron
Report : Perceptron
1. 퍼셉트론이란?
생물학적 뉴런을 모방한 가장 기본적인 인공신경망
입력 값 × 가중치 + 바이어스를 통해 선형결합을 만들고, 단위 계단 함수(step function) 로 0 또는 1을 출력
간단한 구조지만, 선형 분리 가능한 문제는 완벽하게 해결할 수 있음
하나의 직선으로 나눌 수 있으면 → 선형 분리 가능
단위 계산 함수 : 입력값이 0보다 크면 1을 출력하고, 그 외엔 0을 출력하는 함수
2. 퍼셉트론 학습 방식 (코드 중심)
# AND & OR & NAND & XOR Gate Perceptron
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x > 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for xi, target in zip(X, y):
prediction = self.predict(xi)
update = self.lr * (target - prediction)
self.weights += update * xi
self.bias += update
total_error += int(update != 0.0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# AND 게이트 데이터 및 학습
X_and = np.array([[0,0],[0,1],[1,0],[1,1]])
y_and = np.array([0,0,0,1])
print(" AND Gate Training")
ppn_and = Perceptron(input_size=2)
ppn_and.train(X_and, y_and)
print("\n AND Gate Test:")
for x in X_and:
print(f"Input: {x}, Predicted Output: {ppn_and.predict(x)}")
# OR 게이트 데이터 및 학습
X_or = np.array([[0,0],[0,1],[1,0],[1,1]])
y_or = np.array([0,1,1,1])
print("\n OR Gate Training")
ppn_or = Perceptron(input_size=2)
ppn_or.train(X_or, y_or)
print("\n OR Gate Test:")
for x in X_or:
print(f"Input: {x}, Predicted Output: {ppn_or.predict(x)}")
# NAND 게이트 데이터 및 학습
X_nand = np.array([[0,0],[0,1],[1,0],[1,1]])
y_nand = np.array([1,1,1,0]) # AND와 반대
print("\n NAND Gate Training")
ppn_nand = Perceptron(input_size=2)
ppn_nand.train(X_nand, y_nand)
print("\n NAND Gate Test:")
for x in X_nand:
print(f"Input: {x}, Predicted Output: {ppn_nand.predict(x)}")
# XOR 게이트 데이터 및 학습
X_xor = np.array([[0,0],[0,1],[1,0],[1,1]])
y_xor = np.array([0,1,1,0]) # 선형 분리 불가능
print("\n XOR Gate Training")
ppn_xor = Perceptron(input_size=2)
ppn_xor.train(X_xor, y_xor)
print("\n XOR Gate Test:")
for x in X_xor:
print(f"Input: {x}, Predicted Output: {ppn_xor.predict(x)}")
2-1. train() 함수 호출
ppn_and.train(X_and, y_and)
X_and: 입력 데이터 배열 (예: [0,0], [1,1] 등)
y_and: 각 입력에 대한 정답 출력값
2-2. 전체 반복 (epoch) 시작
for epoch in range(self.epochs): # 총 10번 반복
한 epoch는 전체 데이터를 한 번 학습하는 주기
총 10번 반복하면서 조금씩 가중치를 조정
2-3. 한 epoch 내 샘플 반복
for xi, target in zip(X, y):
각 데이터 xi와 정답 target을 하나씩 꺼내 순차 학습
2-4. 예측 과정
prediction = self.predict(xi)
predict() 내부에서 다음 순서로 작동:
linear_output = w·x + b
activation() → 0 또는 1 반환
2-5. 오차 계산 및 가중치/바이어스 업데이트
update = self.lr * (target - prediction)
예측이 정답보다 작으면 → update > 0: 가중치 증가
예측이 정답보다 크면 → update < 0: 가중치 감소
예측이 정확하면 → update == 0: 가중치 변화 없음
self.weights += update * xi
self.bias += update
각 입력 값에 따라 가중치 조정
항상 바이어스도 같이 업데이트
2-6. 에러 카운트
total_error += int(update != 0.0)
예측이 틀렸을 때만 에러로 집계
2-7. 학습 결과 출력
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
학습이 진행될수록 Errors가 줄어드는지 확인 가능
하지만 XOR은 줄지 않음 → 선형 분리 불가능 문제
2-8. 최종 예측 결과 확인
각 게이트에 대해 학습이 끝나면 다음을 수행:
for x in X_and:
print(f"Input: {x}, Predicted Output: {ppn_and.predict(x)}")
학습된 가중치로 새로운 입력을 테스트해보는 과정
2-9. 요약: 퍼셉트론 학습 흐름
입력 X, 정답 y
→ 가중합 계산 (w·x + b)
→ 계단 함수로 예측
→ 오차 계산 (target - predict)
→ w, b 업데이트
→ 에러 기록
→ epoch 반복
→ 학습 완료 후 테스트
3. XOR 게이트가 퍼셉트론으로 안 되는 이유
퍼셉트론은 직선 하나로 출력을 나누는 모델
XOR은 어떤 직선으로도 0과 1을 나눌 수 없음
즉, 선형 분리 불가능 문제 → 퍼셉트론 한계
해결책: 다층 퍼셉트론 (MLP)
비선형성을 처리하기 위해 은닉층 + 비선형 활성화 함수 (예: sigmoid, ReLU)를 활용하고,
오차 역전파(Backpropagation)로 학습함
-
Day3 : Perceptron
📌 Perceptron란?
퍼셉트론(Perceptron)은 생물학적 뉴런을 수학적으로 모델링한 인공 뉴런 모델로, 여러 입력 신호를 받아 각 입력에 대한 가중치(Weight)를 곱한 후, 이들의 가중합(Weighted Sum)을 계산하고, 활성화 함수(Activation Function)를 통해 최종 출력을 결정하는 구조이다.
🔧 구조 (Perceptron Structure)
입력(x) → 가중치(w) → 가중합(∑) → 활성화 함수(f) → 출력(y)
입력 (Input): AND, OR 등 논리 연산을 위한 입력 신호.
가중치 (Weight): 입력 신호의 중요도를 결정하며, 학습을 통해 조정됨.
가중합 (Weighted Sum): 각 입력과 그에 대응하는 가중치의 곱을 모두 더한 값.
활성화 함수 (Activation Function): 가중합이 임계값을 넘으면 1, 넘지 못하면 0을 출력하는 함수. 대표적으로 단위 계단 함수 사용.
출력 (Output): 최종 결과값 (보통 0 또는 1의 이진 출력).
🎯 요약
퍼셉트론은 이진 분류 문제를 해결할 수 있는 가장 기본적인 신경망 구조이다.
학습을 통해 입력 신호의 중요도를 나타내는 가중치가 조정된다.
단층 퍼셉트론은 선형 분리 가능한 문제만 해결할 수 있다.
👨💻 실습
💡 Code : AND & OR & NAND & XOR Gate Perceptron
# AND & OR & NAND & XOR Gate Perceptron
import numpy as np
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, input_size, lr=0.1, epochs=10):
self.weights = np.zeros(input_size)
self.bias = 0
self.lr = lr
self.epochs = epochs
self.errors = []
def activation(self, x):
return np.where(x > 0, 1, 0)
def predict(self, x):
linear_output = np.dot(x, self.weights) + self.bias
return self.activation(linear_output)
def train(self, X, y):
for epoch in range(self.epochs):
total_error = 0
for xi, target in zip(X, y):
prediction = self.predict(xi)
update = self.lr * (target - prediction)
self.weights += update * xi
self.bias += update
total_error += int(update != 0.0)
self.errors.append(total_error)
print(f"Epoch {epoch+1}/{self.epochs}, Errors: {total_error}")
# AND 게이트 데이터 및 학습
X_and = np.array([[0,0],[0,1],[1,0],[1,1]])
y_and = np.array([0,0,0,1])
print(" AND Gate Training")
ppn_and = Perceptron(input_size=2)
ppn_and.train(X_and, y_and)
print("\n AND Gate Test:")
for x in X_and:
print(f"Input: {x}, Predicted Output: {ppn_and.predict(x)}")
# OR 게이트 데이터 및 학습
X_or = np.array([[0,0],[0,1],[1,0],[1,1]])
y_or = np.array([0,1,1,1])
print("\n OR Gate Training")
ppn_or = Perceptron(input_size=2)
ppn_or.train(X_or, y_or)
print("\n OR Gate Test:")
for x in X_or:
print(f"Input: {x}, Predicted Output: {ppn_or.predict(x)}")
# NAND 게이트 데이터 및 학습
X_nand = np.array([[0,0],[0,1],[1,0],[1,1]])
y_nand = np.array([1,1,1,0]) # AND와 반대
print("\n NAND Gate Training")
ppn_nand = Perceptron(input_size=2)
ppn_nand.train(X_nand, y_nand)
print("\n NAND Gate Test:")
for x in X_nand:
print(f"Input: {x}, Predicted Output: {ppn_nand.predict(x)}")
# XOR 게이트 데이터 및 학습
X_xor = np.array([[0,0],[0,1],[1,0],[1,1]])
y_xor = np.array([0,1,1,0]) # 선형 분리 불가능
print("\n XOR Gate Training")
ppn_xor = Perceptron(input_size=2)
ppn_xor.train(X_xor, y_xor)
print("\n XOR Gate Test:")
for x in X_xor:
print(f"Input: {x}, Predicted Output: {ppn_xor.predict(x)}")
✅ Result : AND & OR & NAND & XOR Gate Perceptron
AND Gate Training
Epoch 1/10, Errors: 1
Epoch 2/10, Errors: 3
Epoch 3/10, Errors: 3
Epoch 4/10, Errors: 2
Epoch 5/10, Errors: 1
Epoch 6/10, Errors: 0
Epoch 7/10, Errors: 0
Epoch 8/10, Errors: 0
Epoch 9/10, Errors: 0
Epoch 10/10, Errors: 0
AND Gate Test:
Input: [0 0], Predicted Output: 0
Input: [0 1], Predicted Output: 0
Input: [1 0], Predicted Output: 0
Input: [1 1], Predicted Output: 1
OR Gate Training
Epoch 1/10, Errors: 1
Epoch 2/10, Errors: 2
Epoch 3/10, Errors: 1
Epoch 4/10, Errors: 0
Epoch 5/10, Errors: 0
Epoch 6/10, Errors: 0
Epoch 7/10, Errors: 0
Epoch 8/10, Errors: 0
Epoch 9/10, Errors: 0
Epoch 10/10, Errors: 0
OR Gate Test:
Input: [0 0], Predicted Output: 0
Input: [0 1], Predicted Output: 1
Input: [1 0], Predicted Output: 1
Input: [1 1], Predicted Output: 1
NAND Gate Training
Epoch 1/10, Errors: 2
Epoch 2/10, Errors: 3
Epoch 3/10, Errors: 3
Epoch 4/10, Errors: 0
Epoch 5/10, Errors: 0
Epoch 6/10, Errors: 0
Epoch 7/10, Errors: 0
Epoch 8/10, Errors: 0
Epoch 9/10, Errors: 0
Epoch 10/10, Errors: 0
NAND Gate Test:
Input: [0 0], Predicted Output: 1
Input: [0 1], Predicted Output: 1
Input: [1 0], Predicted Output: 1
Input: [1 1], Predicted Output: 0
XOR Gate Training
Epoch 1/10, Errors: 2
Epoch 2/10, Errors: 3
Epoch 3/10, Errors: 4
Epoch 4/10, Errors: 4
Epoch 5/10, Errors: 4
Epoch 6/10, Errors: 4
Epoch 7/10, Errors: 4
Epoch 8/10, Errors: 4
Epoch 9/10, Errors: 4
Epoch 10/10, Errors: 4
XOR Gate Test:
Input: [0 0], Predicted Output: 1
Input: [0 1], Predicted Output: 1
Input: [1 0], Predicted Output: 0
Input: [1 1], Predicted Output: 0
💡 Code : 경계 결정 시각화 함수 (AND, OR, NAND, XOR)
# 경계 결정 시각화 함수 (AND, OR, NAND, XOR)
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
def plot_decision_boundary(X, y, model, title='Perceptron Decision Boundary'):
cmap_light = ListedColormap(['#FFDDDD', '#DDDDFF']) # 배경 색상
cmap_bold = ListedColormap(['#FF0000', '#0000FF']) # 점 색상
h = .02 # mesh grid 간격
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.figure(figsize=(6, 5))
plt.contourf(xx, yy, Z, cmap=cmap_light)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold,
edgecolor='k', s=100, marker='o')
plt.xlabel('Input 1')
plt.ylabel('Input 2')
plt.title(title)
plt.grid(True)
plt.show()
# AND 게이트 결정 경계 시각화
plot_decision_boundary(X_and, y_and, ppn_and, title='AND Gate Decision Boundary')
# OR 게이트 결정 경계 시각화
plot_decision_boundary(X_or, y_or, ppn_or, title='OR Gate Decision Boundary')
# NAND 게이트 결정 경계 시각화
plot_decision_boundary(X_nand, y_nand, ppn_nand, title='NAND Gate Decision Boundary')
# XOR 게이트 결정 경계 시각화
plot_decision_boundary(X_xor, y_xor, ppn_xor, title='XOR Gate Decision Boundary')
✅ Result : 경계 결정 시각화 함수 (AND, OR, NAND, XOR)
💡 Code : # 오류 시각화 (AND, OR, NAND, XOR)
# 오류 시각화 (AND, OR, NAND, XOR)
plt.figure(figsize=(8, 5))
plt.plot(range(1, len(ppn_and.errors) + 1), ppn_and.errors, marker='o', label='AND Gate')
plt.plot(range(1, len(ppn_or.errors) + 1), ppn_or.errors, marker='s', label='OR Gate')
plt.plot(range(1, len(ppn_nand.errors) + 1), ppn_nand.errors, marker='^', label='NAND Gate')
plt.plot(range(1, len(ppn_xor.errors) + 1), ppn_xor.errors, marker='x', label='XOR Gate')
plt.xlabel('Epochs')
plt.ylabel('Number of Errors')
plt.title('Perceptron Learning Error Over Epochs')
plt.legend()
plt.grid(True)
plt.show()
✅ Result : 오류 시각화 (AND, OR, NAND, XOR)
💬 Comment
퍼셉트론: 입력 벡터에 가중치를 곱한 합이 기준(0)을 넘는지 판단하고, 학습 과정에서는 틀린 만큼만 조정하며 선형 분리를 배우는 구조
XOR은 선형 분리 불가능한 문제이기 때문에
단층 퍼셉트론으로는 해결할 수 없다.
이를 해결하려면 다층 퍼셉트론(MLP)이나 비선형 변환이 필요하다.
💡 Code : MLP로 XOR 문제 해결
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
class MultiLayerPerceptron:
def __init__(self, input_size=2, hidden_size=4, output_size=1, lr=0.5, epochs=1000):
self.W1 = np.random.uniform(-1, 1, (input_size, hidden_size))
self.b1 = np.zeros((1, hidden_size))
self.W2 = np.random.uniform(-1, 1, (hidden_size, output_size))
self.b2 = np.zeros((1, output_size))
self.lr = lr
self.epochs = epochs
self.losses = []
def sigmoid(self, x):
return 1 / (1 + np.exp(-np.clip(x, -250, 250)))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, X):
self.z1 = np.dot(X, self.W1) + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
m = X.shape[0]
dZ2 = output - y
dW2 = (1 / m) * np.dot(self.a1.T, dZ2)
db2 = (1 / m) * np.sum(dZ2, axis=0, keepdims=True)
dZ1 = np.dot(dZ2, self.W2.T) * self.sigmoid_derivative(self.a1)
dW1 = (1 / m) * np.dot(X.T, dZ1)
db1 = (1 / m) * np.sum(dZ1, axis=0, keepdims=True)
self.W2 -= self.lr * dW2
self.b2 -= self.lr * db2
self.W1 -= self.lr * dW1
self.b1 -= self.lr * db1
def train(self, X, y):
for epoch in range(self.epochs):
output = self.forward(X)
loss = np.mean((output - y) ** 2)
self.losses.append(loss)
self.backward(X, y, output)
#if epoch % 200 == 0:
# print(f"Epoch {epoch}/{self.epochs}, Loss: {loss:.6f}")
def predict(self, X):
output = self.forward(X)
return (output > 0.5).astype(int)
def predict_prob(self, X):
return self.forward(X).ravel() # 결정 경계용
# === XOR 데이터 ===
X_xor = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y_xor = np.array([[0], [1], [1], [0]])
# === 학습 ===
print("\n=== XOR Gate Multi-Layer Perceptron Training ===")
mlp = MultiLayerPerceptron(input_size=2, hidden_size=2, lr=0.5, epochs=10000)
mlp.train(X_xor, y_xor)
# === 예측 결과 출력 ===
print("\nXOR GATE Test (Multi-Layer Perceptron):")
xor_predictions = mlp.predict(X_xor)
for i, x in enumerate(X_xor):
predicted = xor_predictions[i][0]
actual = y_xor[i][0]
result = "✓" if predicted == actual else "✗"
print(f"Input: {x}, Predicted: {predicted}, Actual: {actual}, {result}")
# === 결정 경계 시각화 함수 ===
def plot_decision_boundary(X, y, model, title="Decision Boundary"):
cmap_light = ListedColormap(['#FFDDDD', '#DDDDFF'])
cmap_bold = ListedColormap(['#FF0000', '#0000FF'])
h = .01
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
grid = np.c_[xx.ravel(), yy.ravel()]
Z = model.predict_prob(grid)
Z = Z.reshape(xx.shape)
plt.figure(figsize=(6, 5))
plt.contourf(xx, yy, Z > 0.5, cmap=cmap_light)
plt.scatter(X[:, 0], X[:, 1], c=y.ravel(), cmap=cmap_bold,
edgecolor='k', s=120)
plt.title(title)
plt.xlabel("Input 1")
plt.ylabel("Input 2")
plt.grid(True)
plt.show()
# === 결정 경계 시각화 ===
plot_decision_boundary(X_xor, y_xor, mlp, title="XOR MLP Decision Boundary")
# === 손실 곡선 시각화 ===
plt.figure(figsize=(8, 5))
plt.plot(range(mlp.epochs), mlp.losses, color='purple')
plt.title("MLP Training Loss on XOR Problem")
plt.xlabel("Epochs")
plt.ylabel("Mean Squared Error")
plt.grid(True)
plt.show()
✅ Result : MLP로 XOR 문제 해결
=== XOR Gate Multi-Layer Perceptron Training ===
XOR GATE Test (Multi-Layer Perceptron):
Input: [0 0], Predicted: 0, Actual: 0, ✓
Input: [0 1], Predicted: 1, Actual: 1, ✓
Input: [1 0], Predicted: 1, Actual: 1, ✓
Input: [1 1], Predicted: 0, Actual: 0, ✓
-
Day2 : OpenCV
📌 OpenCV란?
OpenCV(Open Source Computer Vision Library)는 실시간 컴퓨터 비전 및 머신러닝을 위한 오픈소스 라이브러리입니다.
다양한 이미지/비디오 처리 기능을 제공하며, Python, C++, Java 등 다양한 언어에서 사용 가능합니다.
🚀 CUDA 모듈의 역할
GPU 가속을 활용한 고속 이미지 처리 수행
OpenCV의 일부 함수들은 CUDA를 통해 병렬 처리되어 성능을 향상시킴
사용 예: cv2.cuda.GpuMat, cv2.cuda.filter2D(), cv2.cuda.resize() 등
🛠️ 작업할 디렉토리 생성 및 환경 설정
# 1. 작업 디렉토리 생성
mkdir opencv # 디렉토리 이름: opencv
cd opencv # 해당 디렉토리로 이동
# 2. 가상 환경 생성 및 활성화
python3 -m venv .env # 가상 환경 생성 (폴더 이름: .env)
source .env/bin/activate # 가상 환경 활성화
# 3. 패키지 설치
pip install opencv-python # OpenCV 기본 기능(core, imgproc 등)
pip install opencv-contrib-python # 추가 모듈(contrib 포함)
pip install -U pip # pip 최신 버전으로 업그레이드
✅ 설치 확인 (Python 인터프리터 실행)
>>> import numpy as np
>>> import cv2
>>> np.__version__
'2.2.6' # 설치된 NumPy 버전 출력
>>> cv2.__version__
'4.11.0' # 설치된 OpenCV 버전 출력
>>> exit() # Python 인터프리터 종료
🎨 색상 정보
🔗 참고 사이트
W3Schools - RGB Colors
🌈 RGB (Red, Green, Blue)
각 색상 채널: 0~255 (8bit)
R (Red): 8bit
G (Green): 8bit
B (Blue): 8bit
픽셀 1개 = 24bit (8bit × 3)
🎨 HSL (Hue, Saturation, Lightness)
H: 색상 (Hue) → 0 ~ 360°
S: 채도 (Saturation) → 0 ~ 100%
L: 밝기 (Lightness) → 0 ~ 100%
🔄 RGB vs HSL 차이점
항목
RGB
HSL
구성
Red, Green, Blue (각 0~255)
Hue (0~360), Saturation & Lightness (0~100%)
직관성
컴퓨터에서 사용하기 적합
사람이 색을 이해하기 쉬움
색 조절
색상 조정이 복잡함
채도/밝기 조절이 용이함
용도
디스플레이, 이미지 처리 등
디자인, 색상 선택 도구 등에 유용
✅ 요약:
RGB는 화면 출력/처리에 적합한 디지털 색 표현 방식
HSL은 색상 구성요소를 분리해 사람이 이해하거나 조절하기 쉬운 방식
📝 메모
vi ex1.py : python 스크립트 생성
python ex1.py : 생성된 스크립트 실행
jpg : 파일이 작고 속도가 빠르며, 주로 사진이나 웹 배경 이미지에 사용
png : 화질 보존, 투명 배경이 필요한 경우 사용
👨💻 실습
💡 Code : 이미지 Read / Write / Display
# ex1.py
import numpy as np
import cv2
# 이미지 파일을 Read
img = cv2.imread("Rengoku.jpg")
# Image 란 이름의 Display 창 생성
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
# Numpy ndarray H/W/C order
print(img.shape)
# Read 한 이미지 파일을 Display
cv2.imshow("image", img)
# 별도 키 입력이 있을때 까지 대기
cv2.waitKey(0)
# ex1_output.jpg 로 읽은 이미지 파일을 저장
cv2.imwrite("ex1_output.jpg", img)
# Destory all windows
cv2.destroyAllWindows()
❓ Quiz: 이미지 Read / Write / Display
1. print(img.shape)의 출력 결과는 무슨 의미일까?
2. 본인이 좋아하는 사진을 web 에서 다운받아서 OpenCV API를 사용해서 Display 및 파일로 저장해보자.
3. 현재는 별도의 키 입력이 있을 때까지 cv2.waitKey(0) 함수에서 대기하게 된다. 코드를 추가해서 소문자 “s” 키를 입력받을 때만 이미지 파일을 저장하고 다른 키가 입력되면 이미지 파일을 저장하지 않게 수정해보자.
💡 Code : RGB/HSV Color Space (색 공간)
# ex2.py
import numpy as np
import cv2
# 이미지 파일을 Read 하고 Color space 정보 출력
color = cv2.imread("Rengoku.jpg", cv2.IMREAD_COLOR)
print(color.shape)
height,width,channels = color.shape
cv2.imshow("Original Image", color)
# Color channel 을 B,G,R 로 분할하여 출력
b,g,r = cv2.split(color)
rgb_split = np.concatenate((b,g,r),axis=1)
cv2.imshow("BGR Channels",rgb_split)
# 색공간을 BGR 에서 HSV 로 변환
hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)
# Channel 을 H,S,V 로 분할하여 출력
h,s,v = cv2.split(hsv)
hsv_split = np.concatenate((h,s,v),axis=1)
cv2.imshow("Split HSV", hsv_split)
❓ Quiz : RGB/HSV Color Space (색 공간)
1. 위 색공간 이미지의 링크로 이동해서 각 색 공간의 표현 방법을 이해해 보자.
2. HSV color space가 어떤 경우에 효과적으로 사용될까?
3. HSV로 변환된 이미지를 BGR이 아닌 RGB로 다시 변환해서 출력해 보자.
4. COLOR_RGB2GRAY를 사용해서 흑백으로 변환해 출력해 보자.
💡 Code : Crop / Resize (자르기 / 크기 조정)
# ex3.py
import numpy as np
import cv2
# 이미지 파일을 Read
img = cv2.imread("Rengoku.jpg")
# Crop 300x400 from original image from (100, 50)=(x, y)
# 세로(y): 100:500 → 500 - 100 = 400픽셀
# 가로(x): 500:1200 → 1200 - 500 = 700픽셀
cropped = img[100:500, 500:1200]
# Resize cropped image from 300x400 to 400x200
resized = cv2.resize(cropped, (800,200))
# Display all
cv2.imshow("Original", img)
cv2.imshow("Cropped image", cropped)
cv2.imshow("Resized image", resized)
cv2.imwrite("ex3_cropped.jpg", cropped)
cv2.imwrite("ex3_resized.jpg", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
❓ Quiz : Crop / Resize (자르기 / 크기 조정)
1. Input image 를 본인이 좋아하는 인물 사진으로 변경해서 적용하자. 그리고 본인이 사용한 input image 의 size 를 확인해 보자.
2. 본인이 사용한 이미지의 얼굴 영역만 crop 해서 display 해 보자.
3. 원본 이미지의 정확히 1.5배만큼 이미지를 확대해서 파일로 저장해 보자.
4. openCV 의 rotate API 를 사용해서 우측으로 90도만큼 회전된 이미지를 출력해 보자.
💡 Code : 역상 (Reverse Image)
# ex4.py
import numpy as np
import cv2
src = cv2.imread("Rengoku.jpg", cv2.IMREAD_COLOR)
dst = cv2.bitwise_not(src)
cv2.imshow("src", src)
cv2.imshow("dst", dst)
cv2.imwrite("ex4_reverse.jpg", dst)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 역상 (Reverse Image)
1. AND, OR, XOR 연산에 대해서 확인해 보자.
💡 Code : 이진화 (Binary)
# ex5.py
import numpy as np
import cv2
src = cv2.imread("Rengoku.jpg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
ret, dst = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
cv2.imshow("dst", dst)
cv2.imwrite("ex5_binary.jpg", dst)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 이진화 (Binary)
1. 임계값을 변화시켜 보자.
💡 Code : 흐림효과 (Blur)
# ex6.py
import numpy as np
import cv2
src = cv2.imread("Rengoku.jpg", cv2.IMREAD_COLOR)
dst = cv2.blur(src, (9, 9), anchor=(-1,- 1), borderType=cv2.BORDER_DEFAULT)
cv2.imshow("dst", dst)
cv2.imwrite("ex6_blur.jpg", dst)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 흐림효과 (Blur)
1. Kernel Size를 변경하여 보자.
2. borderType을 변경하여 보자.(cv2.BORDER_REFLECT)
💡 Code : 가장자리 검출 (Edge)
# ex7.py
import numpy as np
import cv2
src = cv2.imread("Rengoku.jpg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, 3)
cv2.imshow("sobel", sobel)
cv2.imwrite("ex7_edge.jpg", sobel)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 가장자리 검출 (Edge)
1. Laplacian 변환을 적용해 보자.
2. Canny Edge Detection을 적용해 보자.
💡 Code : 배열 병합 (add Weighted)
# ex8.py
import numpy as np
import cv2
src = cv2.imread("RGB.png", cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
# 1. Red 마스크 생성
lower_red = cv2.inRange(hsv, (0, 100, 100), (5, 255, 255))
upper_red = cv2.inRange(hsv, (170, 100, 100), (180, 255, 255))
mask_red = cv2.addWeighted(lower_red, 1.0, upper_red, 1.0, 0.0)
# 2. Green 마스크 생성
mask_green = cv2.inRange(hsv, (40, 100, 100), (85, 255, 255))
# 3. Blue 마스크 생성
mask_blue = cv2.inRange(hsv, (100, 100, 100), (130, 255, 255))
# 4. 각 색상 추출 (HSV → BGR 변환 포함)
red = cv2.bitwise_and(hsv, hsv, mask=mask_red)
green = cv2.bitwise_and(hsv, hsv, mask=mask_green)
blue = cv2.bitwise_and(hsv, hsv, mask=mask_blue)
red = cv2.cvtColor(red, cv2.COLOR_HSV2BGR)
green = cv2.cvtColor(green, cv2.COLOR_HSV2BGR)
blue = cv2.cvtColor(blue, cv2.COLOR_HSV2BGR)
# 5. 화면 출력
cv2.imshow("Original", src)
cv2.imshow("Red", red)
cv2.imshow("Green", green)
cv2.imshow("Blue", blue)
cv2.imwrite("ex8_original.png", src)
cv2.imwrite("ex8_red.png", red)
cv2.imwrite("ex8_green.png", green)
cv2.imwrite("ex8_blue.png", blue)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 배열 병합 (add Weighted)
1. lower_red 값의 범위를 변경해 보자.
2. upper_red 값의 범위를 변경해 보자.
3. addWeighted의 gamma 값을 변경해 보자.
💡 Code : 채널 분리 및 병합
# ex9.py
import numpy as np
import cv2
# 이미지 읽기
src = cv2.imread("RGB.png", cv2.IMREAD_COLOR)
# 채널 분리
b, g, r = cv2.split(src)
# 채널 순서 변경 (RGB처럼 보이게)
inverse = cv2.merge((r, g, b))
# 화면 출력
cv2.imshow("b", b)
cv2.imshow("g", g)
cv2.imshow("r", r)
cv2.imshow("inverse", inverse)
# 이미지 저장
cv2.imwrite("ex9_blue_gray.png", b)
cv2.imwrite("ex9_green_gray.png", g)
cv2.imwrite("ex9_red_gray.png", r)
cv2.imwrite("ex9_inverse.png", inverse)
cv2.waitKey()
cv2.destroyAllWindows()
❓ Quiz : 채널 분리 및 병합
1. Numpy 형태의 채널 분리를 적용해 보자.
b = src[:, :, 0]
g = src[:, :, 1]
r = src[:, :, 2]
2. 빈 이미지를 적용해 보자.
height, width, channel = src.shape
zero = np.zeros((height, width, 1), dtype=np.uint8)
bgz = cv2.merge((b, g, zero))
💡 Code : 동영상 파일을 읽고 보여주기
# ex10.py
import numpy as np
import cv2
cap = cv2.VideoCapture("son.mp4")
save_count = 1 # 저장할 이미지 번호 초기화
while cap.isOpened():
ret, frame = cap.read()
# (2) 프레임 읽기 실패 → 영상 끝 → 처음부터 다시
if not ret:
print("Restarting video...")
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
continue
# (3) 프레임 크기 50% 축소
resized = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
# 출력
cv2.imshow("Resized Frame", resized)
# (1) 고정된 속도로 재생 (약 30fps)
key = cv2.waitKey(90)
# (4) 'c' 키 입력 시 이미지 저장
if key & 0xFF == ord('c'):
filename = f"{save_count:03}.jpg"
cv2.imwrite(filename, resized)
print(f"Saved {filename}")
save_count += 1
# 'q' 키 입력 시 종료
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
❓ Quiz : 동영상 파일을 읽고 보여주기
1. 동영상이 너무 빠르게 재생된다. 이유를 찾아보고 정상적인 속도로 재생될 수 있도록 수정해 보자.
2. 동영상이 끝까지 재생되면 더 이상 frame을 읽지 못해 종료된다. 동영상이 끝까지 재생되면 다시 처음부터 반복될 수 있도록 수정해 보자.
3. 동영상 크기를 반으로 resize해서 출력해 보자.
4. 동영상 재생 중 'c' 키 입력을 받으면 해당 프레임을 이미지 파일로 저장하는 코드를 작성해 보자. 파일 이름은 001.jpg, 002.jpg 등으로 overwrite 되지 않게 하자.
💡 Code : 카메라로부터 input 을 받아 보여주고 동영상 파일로 저장하기
# ex11.py
import numpy as np
import cv2
# Read from the first camera device
cap = cv2.VideoCapture(0)
w = 640 #1280#1920
h = 480 #720#1080
cap.set(cv2.CAP_PROP_FRAME_WIDTH, w)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, h)
# 성공적으로 video device 가 열렸으면 while 문 반복
while(cap.isOpened()):
# 한 프레임을 읽어옴
ret, frame = cap.read()
if ret is False:
print("Can't receive frame (stream end?). Exiting ...")
break
# Display
cv2.imshow("Camera", frame)
# 1 ms 동안 대기하며 키 입력을 받고 'q' 입력 시 종료
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
❓ Quiz : 카메라로부터 input 을 받아 보여주고 동영상 파일로 저장하기
1. 가지고 있는 카메라의 지원 가능한 해상도를 확인 후 카메라 해상도를 변경해 보자.
2. 카메라 Input을 "output.mp4" 동영상 파일로 저장하도록 코드를 추가해 보자.
📝 메모
sudo apt install v4l-utils : 카메라 지원 해상도 확인용 도구 설치
v4l2-ctl -d /dev/video0 –list-formats-ext : 해당 카메라의 해상도 및 포맷 목록 출력
💡 Code : Text / Line / Ractangle
# ex12.py
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# 동그라미를 그릴 좌표를 저장할 리스트
circle_centers = []
def draw_circle(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
# 마우스 왼쪽 버튼 클릭 시 좌표 저장
circle_centers.append((x, y))
cv2.namedWindow("Camera")
cv2.setMouseCallback("Camera", draw_circle)
topLeft = (50+100, 50)
bottomRight = (300+100, 300)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Line
cv2.line(frame,
(topLeft[0] + 80, topLeft[1]),
(bottomRight[0] + 80, bottomRight[1]),
(0, 255, 0), 3)
# Rectangle
cv2.rectangle(frame,
[pt+80 for pt in topLeft], [pt+50 for pt in bottomRight], (255, 0, 255), 3)
# Text
font = cv2.FONT_ITALIC
cv2.putText(frame, 'hhhong',
[pt-180 for pt in bottomRight], font, 2, (0, 255, 255), 5)
# 저장된 좌표에 동그라미 그리기
for center in circle_centers:
cv2.circle(frame, center, 30, (255, 255, 0), 3) # 반지름 30, 두께 3, 색상 (BGR)
cv2.imshow("Camera", frame)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
❓ Quiz : Text / Line / Ractangle
1. Text 문구 / Font / 색상 / 크기 / 굵기 / 출력위치 등 모든 값을 변경해 보자.
2. 동그라미를 그리는 함수를 찾아서 적용해 보자.
3. 마우스 왼쪽 버튼을 click 하면 해당 위치에 동그라미가 그려지도록 코드를 추가해 보자.
(Reference : cv2.EVENT_LBUTTONDOWN)
💡 Code : Trackbar
# ex13.py
import cv2
topLeft = (50, 50)
bold = 0
r, g, b = 255, 255, 0 # 초기 텍스트 색상: 노란색 (BGR = (0, 255, 255))
# bold 트랙바 콜백
def on_bold_trackbar(value):
global bold
bold = value
global r
r = value
def on_g_trackbar(value):
global g
g = value
def on_b_trackbar(value):
global b
b = value
# 카메라 연결
cap = cv2.VideoCapture(0)
# 윈도우 및 트랙바 생성
cv2.namedWindow("Camera")
cv2.createTrackbar("bold", "Camera", bold, 30, on_bold_trackbar)
cv2.createTrackbar("R", "Camera", r, 255, on_r_trackbar)
cv2.createTrackbar("G", "Camera", g, 255, on_g_trackbar)
cv2.createTrackbar("B", "Camera", b, 255, on_b_trackbar)
# 루프 시작
while cap.isOpened():
ret, frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
# 텍스트 출력 (트랙바에서 받아온 bold, color 값 사용)
cv2.putText(frame, "hhhong",
topLeft,
cv2.FONT_HERSHEY_SIMPLEX,
2,
(b, g, r), # BGR
1 + bold)
# 프레임 출력
cv2.imshow("Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 종료 처리
cap.release()
cv2.destroyAllWindows()
❓ Quiz: Trackbar
1. Trackbar를 control해서 TEXT의 굵기가 변하는 것을 확인해 보자.
2. Trackbar를 추가해서 font size를 변경 / 적용해 보자.
3. R/G/B Trackbar를 각각 추가해서 글자의 font color를 변경해 보자.
-
-
2025-06-17 study
What is Lorem Ipsum?
This is an example post ‘<’. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
찬하꺼대로
Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ‘Content here, content here’, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of “de Finibus Bonorum et Malorum” (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32.
The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from “de Finibus Bonorum et Malorum” by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don’t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn’t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
This is the bold text and this is the italic text and let’s do strikethrough.
Don’t forget to code your dream.
Fruits:
🍎
🍋
Other fruits:
🍑
🍏
Numbers:
first
second
third
Click here
| Header | Description |
| :–: | :–: |
| Cell1 | Cell2 |
| Cell1 | Cell2 |
| Cell1 | Cell2 |
| Cell1 | Cell2 |
To print message in the console, use console.log('your message') and ..
console.log('your message')
하윙
-
-
-
-
-
[ex64] 배열에서 패턴 개수 찾기 (10점)
문제 설명
20글자 이하의 문자열이 입력되어 s1 배열에 저장되고 5글자 이하의 문자열이 입력되어 s2 배열에 저장된다.
문자열 s1에서 s2와 같은 패턴의 문자열이 몇개가 존재하는지 개수를 인쇄하라
만약 s1이 abababac 이고 s2가 aba일 경우 총 3번 aba 패턴이 존재하므로 답은 3이 된다.
아래 코드를 사용하되 변수, 함수는 임의로 추가하여 사용하면 된다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main(void)
{
char s1[21];
char s2[6];
scanf(" %s", s1);
scanf(" %s", s2);
// 코드 작성
}
입력 예시
abababac
aba
출력 예시
3
정답 코드
#if 0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main(void)
{
char s1[21];
char s2[6];
scanf(" %s", s1);
scanf(" %s", s2);
int i, j, cnt = 0;
for (i = 0; s1[i] != '\0'; i++)
{
for (j = 0; ; j++)
{
if (s2[j] == '\0')
{
cnt++;
break;
}
else if ((s1[j + i] != s2[j]) || (s1[j + i] == '\0'))
{
break;
}
}
}
printf("%d\n", cnt);
}
#endif
/* 함수로 설계 */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int str_cmp(char * p, char * q)
{
int i;
for (i = 0; ; i++)
{
if (q[i] == '\0') return 1;
if ((p[i] != q[i]) || (p[i] == '\0')) return 0;
}
}
void main(void)
{
char s1[21];
char s2[6];
scanf(" %s", s1);
scanf(" %s", s2);
int i, cnt = 0;
for (i = 0; s1[i] != '\0'; i++)
{
cnt += str_cmp(&s1[i], s2);
}
printf("%d\n", cnt);
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
[ex59] 가위 바위 보 판정하기 (10점)
문제 설명
a와 b 두 사람이 가위, 바위, 보 게임을 하려고 한다.
가위는 0, 바위는 1, 보는 2를 입력하게 되며
승부 결과는 a가 이기면 a, b가 이기면 b 비기면 =을 인쇄하면 된다.
즉, 0 0, 1 1, 2 2와 같이 같은 것을 내면 비기므로 =가 나와야 하고
0 1 이렇게 되면 a는 가위 b는 바위이므로 b가 이겨서 b가 인쇄되어야 한다.
아래 코드를 이용하여 작성하되 필요한 변수 등은 자유롭게 추가가 가능하다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main(void)
{
int a, b;
scanf("%d %d", &a, &b);
// 코드 작성
}
입력 예시
0 1
출력 예시
b
정답 코드
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
char r[3][3] = { {'=','b','a'},{'a','=','b'},{'b','a','='} };
void main(void)
{
int a, b;
scanf("%d %d", &a, &b);
printf("%c\n", r[a][b]);
}
메모
printf 내부의 \n 습관화 필요
-
[ex58] 만기 적금 계산 함수 (10점)
문제 설명
다음 조건을 만족하는 적금 만기액을 구하는 함수를 설계하라
(1) 원금(total), 일 이자액(rate), 가입 일수(day)를 전달 받는다.
(2) 가입일(day) 1일마다 월 이자액(rate) 만큼 원금에 이자가 붙는다.
(3) 다만, 최종 지급액은 100원 미만 금액은 절사하여 결정한다.
예를 들어 total이 12,310원, rate가 40원, day가 9일이라면 총 이자는 360원이므로 총 금액은 12,670원이다.
그러나 100원 미만 절사하게 되므로 최종 지급금은 12,600원이 된다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int money(int total, int rate, int day)
{
// 코드 작성
}
void main(void)
{
int t, r, d;
scanf("%d %d %d", &t, &r, &d);
printf("%d\n", money(t, r, d));
}
입력 예시
12310 40 9
출력 예시
12600
정답 코드
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int money(int total, int rate, int day)
{
total = (total + rate * day);
return total - total % 100;
}
void main(void)
{
int t, r, d;
scanf("%d %d %d", &t, &r, &d);
printf("%d\n", money(t, r, d));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
[ex54] 두 개의 문자열을 교환하는 Swap 함수를 구현하시오
문제 설명
두 개의 문자열을 교환하는 Swap 함수를 구현하시오. (필요시 함수 추가 설계하여 구현한다.)
다음 코드는 입출력 Template으로 복사하여 코드를 작성하고 제시한 함수( Swap() )를 직접 구현하여 완성한다.
#include < stdio.h>
// 필요시 함수 추가 설계 (예)문자열을 복사하는 함수
// 여기에 Swap()함수를 구현한다
int main(void)
{
char a[110], b[110];
scanf("%s %s", a, b);
Swap( a, b );
printf("%s %s\n", a, b);
return 0;
}
입력 설명
문자열 2개를 입력받는다
출력 설명
교환한 문자열을 출력한다
입력 예시
Hi Hello
출력 예시
Hello Hi
정답 코드
#include <stdio.h>
void str_copy( char *d, const char *s)
{
while(*d++=*s++);
}
void Swap(char *ap, char *bp)
{
char temp[110];
str_copy(temp,ap);
str_copy(ap,bp);
str_copy(bp,temp);
}
int main(void)
{
char a[110], b[110];
scanf("%s %s", a, b);
Swap( a, b );
printf("%s %s\n", a, b);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
[ex50] 같은 모양 찾기 simple
문제 설명
아래와 같이 모눈종이에 각각의 칸들이 칠해져 있는 그림이 있을 때 모눈종이에서 찾고 싶은 패턴의 모양이 몇 개가 있는지를 검사하려고 한다. 이 때, 찾고자 하는 모눈종이의 크기 M(0≤M≤100)과 패턴의 크기 P(0≤P≤100)은 주어진다.
찾고자 하는 패턴의 모양은 회색과 흰색으로 칠해지고, 패턴은 같은 모양만 찾으면 된다. 또한 회색으로 칠해진 칸은 패턴 매치 검사 시 반복되어 사용될 수 있다.
#include <stdio.h>
int main(void)
{
// 여기서부터 작성
return 0;
}
입력 설명
첫 번째 줄에는 모눈종이이의 크기 M(0≤M≤100)이 주어진다.
두 번째 줄부터 M 줄까지는 모눈종이에 그린 그림을 칠한 칸은 1로, 칠하지 않은 칸은 0으로 모눈종이의 줄 별로 입력한다.
다음 줄에는 패턴의 크기 P(0≤P≤100)가 주어진다. 다음 줄부터 P개의 줄에 걸쳐 찾고 싶은 패턴의 모양이 주어진다. 모양이 있는 부분만 1 로 입력하고 나머지는 0으로 처리한다.
출력 설명
출력은 찾고 싶은 패턴의 모양이 모눈종이에 그린 그림에 몇 개가 있는지 그 개수를 출력한다.
입력 예시
10
0000000001
1110000000
0000001000
0000101000
1111111111
0000101000
0000001000
0000000000
1110000000
0000000001
3
100
111
100
출력 예시
1
정답 코드
#include <stdio.h>
int maa[110][110], b[110][110];
int N,P;
int pattern(int k, int m)
{
int i, j;
int sol = 0;
for (i = 0; i < N ; i++)
{
for (j = 0; j < N ; j++)
{
if (maa[i + k][j + m] == b[i][j])
{
sol++;
}
}
}
return sol;
}
int main(void)
{
int i, j;
scanf("%d", &P);
for (i = 0; i < P; i++)
{
for (j = 0; j < P; j++)
{
scanf("%1d", &maa[i][j]);
}
}
scanf("%d", &N);
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
scanf("%1d", &b[i][j]);
}
}
int Num = 0;
for (i = 0; i <= P - N; i++)
{
for (j = 0; j <= P - N; j++)
{
if (pattern(i, j) == N*N)
{
Num++;
}
}
}
printf("%d ", Num);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex49] 가장 큰 숫자와 가장 큰 숫자가 있는 행과 열 변호 인쇄
문제 설명
a[5][4] 배열을 대상으로 아래 결과를 인쇄하는 코드를 설계하라
배열에서 가장 큰 숫자가 포함된 행과 열번호 및 최대값을 인쇄
같은 최대값이 여러 줄에 있을 경우 가장 낮은 줄 번호를 인쇄
행과 열의 번호는 0번 행부터 시작한다
#include <stdio.h>
int a[5][4] = { {10,2,-3,4}, {5,-6,7,-8}, {-9,10,-19,12}, {15,-8,7,-8}, {-3,10,9,17} };
void main(void)
{
int i, j;
// 가장 큰 값이 저장된 행 번호, 열번호, 최대값을 찾아서 인쇄한다
}
출력 설명
4 3 17
출력 예시
4 3 17
정답 코드
#include <stdio.h>
int a[5][4] = { {10,2,-3,4}, {5,-6,7,-8}, {-9,10,-19,12}, {15,-8,7,-8}, {-3,10,9,17} };
void main(void)
{
int i, j;
int max = a[0][0];
int max_row = 0;
int max_col = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 4; j++)
{
if (a[i][j] > max)
{
max = a[i][j];
max_row = i;
max_col = j;
}
}
}
printf("%d %d %d", max_row, max_col, max);
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
[ex33] 두 수를 입력 받아서 그 사이에 존재하는 소수를 인쇄하는 프로그램
문제 설명
두 수를 입력 받아 그 사이의 소수를 인쇄하는 함수를 설계하라
main에서 두 수를 입력 받은 함수에 전달하여 두 수 사이의 소수를 인쇄한다
다음 사항을 준수하도록 한다
입력 값이 음수이거나 0이면 다시 입력 받을 것 (즉, 양의 정수만 입력 값으로 사용함)
10 다음 200이 올수도 있지만 200다음 10이 올 수도 있으니 어떤 경우든지 처리되도록 함
잘못된 입력에 대한 예외처리는 main에서 할까 소수인쇄 함수에서 할까?
일반적으로 함수는 단순한 일만 하게 만드는 것이 좋음
결국 main에서 잘못된 입력을 처리해 주고 정상인 값들만 함수로 전달하는 것이 좋음
예외처리 및 입력 코드는 아래 코드 참고
소수는 1은 포함이 되지 않지만 그냥 너그러이 용서해 주세요 1도 소수로 보고 인쇄 해주세요
#include <stdio.h>
void Print_Prime(int min, int max)
{
}
void main(void)
{
int a, b;
scanf(" %d", &a);
scanf(" %d", &b);
if ((a <= 0) || (b <= 0))
{
printf("Error!!\n");
}
else
{
// 코드 구현
Print_Prime(a, b);
}
}
입력 예시
1
20
출력 예시
1
2
3
5
7
11
13
17
19
정답 코드
#include <stdio.h>
void Print_Prime(int min, int max)
{
int i, j, k;
for (i = min; i <= max; i++)
{
k = 0;
for (j = 2; j < i; j++)
{
if ((i % j) == 0)
{
k = 1;
break;
}
}
if (k == 0)
{
printf("%d\n", i);
}
}
}
void main(void)
{
int i, a, b;
scanf(" %d", &a);
scanf(" %d", &b);
if ((a <= 0) || (b <= 0))
{
printf("Error!!\n");
}
else
{
if (a > b)
{
i = a;
a = b;
b = i;
}
Print_Prime(a, b);
}
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
-
-
-
[ex24] 두 개의 정수 중 큰 수를 판별하는 Max_Calc 함수를 구현하시오
문제 설명
[함수 형식] int Max_Calc(int a, int b);
[함수 기능] 넘어온 두 정수 중 큰 수를 판별하여 큰 수를 리턴한다. 같은 값일 경우 그 값을 리턴한다
[main 함수] 2개의 정수를 입력받아 Max_Calc함수를 호출하여 리턴 된 큰 수를 인쇄한다.
#include <stdio.h>
int Max_Calc(int a, int b);
int main(void)
{
//함수작성
return 0;
}
int Max_Calc(int a, int b)
{
//함수작성
}
입력 설명
첫 줄에 두 개의 정수 a, b가 공백으로 구분되어 입력된다. (a, b 모두 int 정수 범위 이내)
출력 설명
입력된 두 수중 큰 수를 인쇄한다.
입력 예시
5 10
출력 예시
10
정답 코드
#include <stdio.h>
int Max_Calc(int a, int b)
{
if(a>=b) return a;
return b;
}
void main(void)
{
int a,b;
scanf("%d %d",&a,&b);
printf("%d\n",Max_Calc(a,b));
}
메모
printf 내부의 \n 습관화 필요
-
[ex23] 성적 계산 함수
문제 설명
다음 조건에 맞는 성적처리 함수를 설계하시오.
parameter는 int이고 함수명은 func, return 타입은 char로 한다.
성적기준은 90~100(‘A’), 80~89(‘B’), 70~79(‘C’), 60~69(‘D’), 60미만(‘F’)이다.
성적을 입력하면 학점(문자 A, B, C, D, F중 하나)을 리턴하는 함수를 설계한다.
단, 지정된 범위의 값이 아니면(음수나 100보다 큰 값) 반드시 문자 ‘X’를 리턴하여 출력한다.
#include <stdio.h>
// 함수 func 설계
void main(void)
{
int score;
scanf("%d", &score);
printf("%c\n", func(score));
}
입력 설명
성적 점수인 정수 하나를 입력받는다. (음수, 양수, 0 모두 가능한 정수)
출력 설명
입력 값에 따른 성적(A, B, C, D, F중 하나)을 출력하고 0~100범위의 수가 아니면 X를 출력한다.
입력 예시
92
출력 예시
A
정답 코드
#include <stdio.h>
char func(int s)
{
if ((s < 0) || (s > 100)) return 'X';
switch (s / 10)
{
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 : return 'F';
case 6 : return 'D';
case 7 : return 'C';
case 8 : return 'B';
case 9 :
case 10: return 'A';
}
}
void main(void)
{
int score;
scanf("%d", &score);
printf("%c\n", func(score));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex20] 2,3,5의 배수 판단하기
문제 설명
2의 배수면 2, 3의 배수면 3, 5의 배수면 5를 2,3,5의 배수가 아니면 0을 리턴하는 함수를 작성하라.
단, 공통배수는 입력되지 않는 것으로 본다
#include <stdio.h>
int compare(int num)
{
}
void main(void)
{
int num;
scanf("%d", &num);
printf("%d\n", compare(num));
}
입력 예시
33
출력 예시
3
정답 코드
#include <stdio.h>
#if 1
int compare(int num)
{
if(num % 2 == 0) return 2;
if(num % 3 == 0) return 3;
if(num % 5 == 0) return 5;
return 0;
}
#endif
#if 0
int compare(int num)
{
int r = 0;
if (num % 2 == 0) r = 2;
else if (num % 3 == 0) r = 3;
else if (num % 5 == 0) r = 5;
return r;
}
#endif
#if 0
int compare(int num)
{
int r = 0;
if ((num % 2) == 0) r = 2;
else if ((num % 3) == 0) r = 3;
else if ((num % 5) == 0) r = 5;
return r;
}
#endif
void main(void)
{
int num;
scanf("%d", &num);
printf("%d\n", compare(num));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
[ex14] 10진수 자리수 분리하기
문제 설명
4자리의 숫자를 입력받아 1000자리 100자리 10자리 1의 자리 값을 각각 인쇄하라
단, 입력은 1000 ~ 9999 사이의 값이며 이외의 숫자는 입력되지 않는다
입력 설명
4자리 숫자 한 개를 입력 받는다. 숫자 N은 1000~9999사이의 값이다.
입력 예시
1234
출력 예시
1000자리=1, 100자리=2, 10자리=3, 1자리=4
정답 코드
#include <stdio.h>
int main()
{
int N, a, b, c, d;
scanf("%d", &N);
if ((N >= 1000) && (N <= 9999))
{
a = N / 1000;
b = (N / 100) % 10;
c = (N / 10) % 10;
d = N % 10;
printf("1000자리=%d, 100자리=%d, 10자리=%d, 1자리=%d\n", a, b, c, d);
}
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex12] /, % 연산자의 활용 => 10진수 자리수 분리
문제 설명
4자리 정수의 각 자리 값을 추출하는 다음 코드를 완성하라
#include <stdio.h>
void main(void)
{
int a = 2345;
int a4, a3, a2, a1;
a4 =
a3 =
a2 =
a1 =
printf("1000자리=%d, 100자리=%d, 10자리=%d, 1자리=%d\n", a4, a3, a2, a1);
}
출력 예시
1000자리=2, 100자리=3, 10자리=4, 1자리=5
정답 코드
#include <stdio.h>
void main(void)
{
int a = 2345;
int a4, a3, a2, a1;
a4 = a / 1000 % 10;
a3 = a / 100 % 10;
a2 = a / 10 % 10;
a1 = a / 1 % 10;
printf("1000자리=%d, 100자리=%d, 10자리=%d, 1자리=%d\n", a4, a3, a2, a1);
}
메모
printf 내부의 \n 습관화 필요
-
[ex11] int 변수로 함수 실행하기
문제 설명
#include <stdio.h>
int func(int a, int b)
{
return a+b;
}
void main(void)
{
int a = (int)func;
printf("%d\n", func(3,4));
printf("%d\n", );
}
정답 코드
#include <stdio.h>
int func(int a, int b)
{
return a+b;
}
typedef int(*FP)(int, int);
void main(void)
{
int a = (int)func;
printf("%d\n", func(3,4) );
printf("%d\n", ((FP)a)(3,4));
// printf("%d\n", ((int (*)(int, int))a)(3, 4));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex08] Type casting 연습 1 (오류 무시)
문제 설명
#include <stdio.h>
void func(int x)
{
printf("%f\n", );
printf("%f\n", );
printf("%f\n", );
}
void main(void)
{
double d[3] = {3.14, 5.125, -7.42};
func((int)d);
}
정답 코드
#include <stdio.h>
void func(int x)
{
/* printf("%f\n", ((double*)x)[0]);
printf("%f\n", ((double*)x)[1]);
printf("%f\n", ((double*)x)[2]);*/
for(i=0; i<3; i++)
{
printf("%f\n", ((double*)x)[i]);
}
}
void main(void)
{
double d[3] = {3.14, 5.125, -7.42};
func((int)d);
}
메모
printf 내부의 \n 습관화 필요
-
[ex07] 함수 Lookup table (코드 수정)
문제 설명
교재의 코드를 그대로 사용하면 안됨(채점을 위하여 get_key 함수 변경됨)
아래 코드 복사하여 fa 배열만 선언할 것
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int mul(int a, int b)
{
return a*b;
}
int get_key(void)
{
static int r = 0;
int ret = r;
r = (r + 1) % 3;
return ret;
}
fa[3] = {add, sub, mul};
int op(int a, int b)
{
return fa[get_key()](a,b);
}
void main(void)
{
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
}
출력 예시
7
-1
12
7
-1
12
7
정답 코드
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int mul(int a, int b)
{
return a*b;
}
int get_key(void)
{
static int r = 0;
int ret = r;
r = (r + 1) % 3;
return ret;
}
int (*fa[3])(int a, int b) = {add, sub, mul};
int op(int a, int b)
{
return fa[get_key()](a,b);
}
void main(void)
{
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
printf("%d\n", op(3, 4));
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex05] 함수 등가포인터의 실행
문제 설명
#include <stdio.h>
int add(int a, int b)
{
return a+b;
}
void f1(void)
{
printf("func\n");
}
int * f2(void)
{
static int a[4] = {1,2,3,4};
return a;
}
void main(void)
{
// p, q, r 선언
// p, q, r에 대응 함수 대입
printf("%d\n", add(3,4));
f1();
printf("%d\n", f2()[2]);
// 위와 동일한 결과가 나오도록 p, q, r로 실행
}
출력 예시
7
func
3
7
func
3
정답 코드
#include <stdio.h>
int add(int a, int b)
{
return a+b;
}
void f1(void)
{
printf("func\n");
}
int * f2(void)
{
static int a[4] = {1,2,3,4};
return a;
}
void main(void)
{
// p, q, r 선언
int (*p)(int a, int b);
void (*q)(void);
int * (*r)(void);
// p, q, r에 대응 함수 대입
p = add;
q = f1;
r = f2;
printf("%d\n", add(3,4));
f1();
printf("%d\n", f2()[2]);
// 위와 동일한 결과가 나오도록 p, q, r로 실행
printf("%d\n", p(3,4));
q();
printf("%d\n", r()[2]);
}
메모
printf 내부의 \n 습관화 필요
-
[ex04] 2차원 배열의 리턴
문제 설명
#include <stdio.h>
func(void)
{
static int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
return a;
}
void main(void)
{
printf("%d\n", func() );
}
출력 예시
7
정답 코드
#include <stdio.h>
int (*func(void))[4]
{
static int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
return a;
}
void main(void)
{
printf("%d\n", func()[1][2]);
}
/* typedef */
#if 0
#include <stdio.h>
typedef int(*ARRP)[4];
ARRP func(void)
{
static int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
return a;
}
void main(void)
{
printf("%d\n", func()[1][2] );
}
#endif
메모
printf 내부의 \n 습관화 필요
-
[ex03] 2차원 배열의 전달
문제 설명
#include <stdio.h>
void draw_pixel(int y, int x, int value, p )
{
p[y][x] = value;
}
void main(void)
{
int a[2][3] = {1,2,3,4,5,6};
printf("%d\n", a[1][2]);
draw_pixel(1, 2, 10, a);
printf("%d\n", a[1][2]);
}
출력 예시
6
10
정답 코드
#include <stdio.h>
void draw_pixel(int y, int x, int value, int (*p)[3])
{
p[y][x] = value;
}
void main(void)
{
int a[2][3] = {1,2,3,4,5,6};
printf("%d\n", a[1][2]);
draw_pixel(1, 2, 10, a);
printf("%d\n", a[1][2]);
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex02] 포인터 배열
문제 설명
배열 a를 이용하여 x[2]를 30으로 만드는 코드를 만드시오
배열 a를 이용하여 x[2]를 30으로 만드는 코드를 만드시오
#include <stdio.h>
int x[4] = {1,2,3,4};
void main(void)
{
int *a[4] = {x+3, x+2, x+1, x};
printf("%d\n", x[2]);
= 30;
printf("%d\n", x[2]);
}
출력 예시
3
30
정답 코드
#include <stdio.h>
int x[4] = {1,2,3,4};
void main(void)
{
int *a[4] = {x+3, x+2, x+1, x};
printf("%d\n", x[2]);
//a[0][-1] = 30;
//a[1][0] = 30;
//a[2][1] = 30;
a[3][2] = 30;
printf("%d\n", x[2]);
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex76] 최대값
문제 설명
9개의 서로 다른 자연수가 주어질 때 이들 중 최대값을 찾고 그 최대값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
예를 들어 서로 다른 9개의 자연수
3, 29, 38, 12, 57, 74, 40, 85, 61
이 주어지면 이들 중 최대값은 85이고 이 값은 8번째 수이다.
#include <stdio.h>
int main(void)
{
return 0;
}
입력 설명
첫 째 줄부터 아홉 번째 줄까지 한 줄에 하나의 자연수가 주어진다. 주어지는 자연수는 100 보다 작다.
출력 설명
첫째 줄에 최대값을 출력하고 둘째 줄에 최대값이 몇 번째 수인지를 출력한다.
입력 예시
3
29
38
12
57
74
40
85
61
출력 예시
85
8
정답 코드
#include <stdio.h>
int A[9];
void InputData(void)
{
for (int i = 0; i < 9; i++)
{
scanf("%d", &A[i]);
}
}
int Solve(void)
{
int maxidx = 0;
for (int i = 1; i < 9; i++)
{
if (A[maxidx] < A[i]) maxidx = i;
}
return maxidx;
}
int main(void)
{
InputData();
int ans = Solve();
printf("%d\n%d\n", A[ans], ans + 1);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex74] 다른 모양의 이차원 배열 Transpose
문제 설명
3x4 배열 a 의 값들을 b 배열(4x3)에 옮겨 저장하라
#include <stdio.h>
int a[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };
int b[4][3];
void transpose2(void)
{
// 코드 구현
}
void main(void)
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
transpose2();
for (i = 0; i < 4; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
출력 예시
1 2 3 4
5 6 7 8
9 10 11 12
12 8 4
11 7 3
10 6 2
9 5 1
정답 코드
#include <stdio.h>
int a[3][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };
int b[4][3];
void transpose2(void)
{
// 코드 구현
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
b[4 - 1 - j][3 - 1 - i] = a[i][j];
}
}
}
void main(void)
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
transpose2();
for (i = 0; i < 4; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
메모
printf 내부의 \n 습관화 필요
-
[ex73] 이차원 배열 Transpose
문제 설명
4x4 배열의 값들을 출력 예시와 같이 b 배열(4x4)에 옮겨 저장하라
#include <stdio.h>
int a[4][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13, 14, 15, 16} };
int b[4][4];
void transpose1(void)
{
// 코드 구현
}
void main(void)
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
transpose1();
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
출력 예시
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
16 12 8 4
15 11 7 3
14 10 6 2
13 9 5 1
정답 코드
#include <stdio.h>
int a[4][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13, 14, 15, 16} };
int b[4][4];
void transpose1(void)
{
// 코드 구현
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
b[4 - 1 - j][4 - 1 - i] = a[i][j];
}
}
}
void main(void)
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
transpose1();
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
[ex68] 성적처리용 수퍼 컴퓨터
문제 설명
성적처리 프로그램을 배열을 이용하여 함수로 설계하라
Parameter는 int이고 함수명과 return 타입은 임의로 지정하라
성적 기준 : 100~91 -> A, 90~81 -> B, 80~71 -> C, 70~61 -> D, 60이하 -> F
성적을 입력하면 학점을 리턴하는 함수를 설계하라 (문자 A,B,C,D,F 중 하나)
단, 지정된 범위의 값(0~100)이 아니면 반드시 문자 X를 리턴 하라
이 프로그램을 배열을 이용하여 최적의 프로그램으로 구현하라
#include <stdio.h>
void main(void)
{
// 코드 작성
}
입력 예시
92
출력 예시
A
정답 코드
#include <stdio.h>
char s[] = "FFFFFFDCBA";
char grade(int score)
{
if (score < 0 || score > 100) return 'X';
return s[(score - 1) / 10];
}
void main(void)
{
int score;
scanf("%d", &score);
printf("%c\n", grade(score));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex65] 밤을 분류하여 담는 바구니
문제 설명
알밤을 종류별로 분류하여 각각의 바구니에 담고자 한다
공백으로 분리된 100 이하의 양의 정수 m, n(m < n)을 입력 받는다
m ~ n 범위의 수 중에서 다음 조건의 알밤들을 저장 한다. (주의) n도 포함 된다
공주 알밤 : 3의 배수, 수원 알밤 : 5의 배수, 쭉정이 : 3 또는 5의 배수가 아닌 수
단, 3과 5의 공배수이면 공주 알밤이며 개수 제한 없이 모든 값을 다 저장해야 한다
먼저 공주 알밤 수와 값들을 인쇄하고 다음에 수원 알밤 수와 값들을 인쇄한다
#include <stdio.h>
void main(void)
{
// 코드 작성
}
입력 예시
1 20
출력 예시
6
3 6 9 12 15 18
3
5 10 20
정답 코드
#include <stdio.h>
int a[100 + 2];
int b[100 + 2];
void main(void)
{
int i, m, n;
int cnt1 = 0, cnt2 = 0;
scanf("%d %d", &m, &n);
for (i = m; i <= n; i++)
{
if ((i % 3) == 0)
{
a[cnt1] = i;
cnt1++;
}
else if ((i % 5) == 0)
{
b[cnt2] = i;
cnt2++;
}
}
printf("%d\n", cnt1);
for (i = 0; i < cnt1; i++)
{
printf("%d ", a[i]);
}
if (cnt1) printf("\n");
printf("%d\n", cnt2);
for (i = 0; i < cnt2; i++)
{
printf("%d ", b[i]);
}
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex63] 알밤만 담는 바구니
문제 설명
최대 10개를 담을 수 있는 알밤 바구니에 알밤들을 담으려 한다
공백으로 분리된 정수 m, n을 입력 받는다
m이 n보다 크거나 m이 음수거나 n이 음수일 경우는 “Error”를 출력하고 종료한다
m ~ n 범위의 수 중에서 다음 조건의 알밤을 저장 한다. (주의) n도 포함 된다
알밤은 3과 5의 공통 배수(15의 배수로 찾지 말고)이고 그 외는 다 쭉정이로 판단한다
바구니는 배열 10개 짜리를 설계하고 알밤을 발견할 때마다 값을 추가한다
단, 알밤은 최대 10개까지만 담을 수 있으며 10개를 담으면 바구니에 저장을 종료해야 한다
바구니에 담긴 알밤 수를 인쇄하고 다음 줄에 공백으로 분리하여 값들을 인쇄한다
단, 알밤이 10개보다 적을 수도 있으며 이 경우 저장된 알밤 값들만 인쇄되어야 한다
#include <stdio.h>
void main(void)
{
// 코드 작성
}
입력 예시
1 50
출력 예시
3
15 30 45
정답 코드
#include <stdio.h>
int a[10];
void main(void)
{
int i, m, n, cnt = 0;
scanf("%d %d", &m, &n);
if (m > n || m < 0 || n < 0)
{
printf("Error\n");
return;
}
for (i = m; i <= n; i++)
{
if (((i % 3) == 0) && ((i % 5) == 0))
{
a[cnt] = i;
cnt++;
if (cnt == 10) break;
}
}
printf("%d\n", cnt);
for (i = 0; i < cnt; i++)
{
printf("%d ", a[i]);
}
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
[ex59] 피타고라스 수
문제 설명
피타고라스는 각 변의 길이가 a, b, c인 직각삼각형에서 a2+b2=c2가 성립함을 발견하고서 유레카를 외치며 목욕탕을 뛰쳐나왔다. (후에 아르키메데스가 이를 따라 했다는 얘기가 있음)
자연수 n이 주어지면, 1≤a≤b≤c≤n을 만족하면서 a2+b2=c2 또한 성립하는 a, b, c가 얼마나 있는지 계산하는 프로그램을 작성하자. 당연히 a, b, c는 모두 정수여야 한다.
예를 들어, n이 15인 경우 아래와 같은 4가지의 (a, b, c)가 존재한다.
(3, 4, 5), (5, 12, 13), (6, 8, 10), (9, 12, 15)
#include <stdio.h>
int Solve(int n)
{
//여기서 부터 작성
}
int main(void)
{
int n;
scanf("%d", &n);
printf("%d\n", Solve(n));
return 0;
}
입력 설명
첫 번째 줄에 300 이하의 자연수 n이 입력된다.
출력 설명
첫 번째 줄에 가능한 피타고라스 수의 개수를 출력한다
입력 예시
15
출력 예시
4
정답 코드
#include <stdio.h>
int Solve(int n)
{
int cnt = 0;
for (int c = 2; c <= n; c++)
{
for (int b = 1; b < c; b++)
{
for (int a = 1; a <= b; a++)
{
if (a*a + b * b == c * c) cnt++;
}
}
}
return cnt;
}
int main(void)
{
int n;
scanf("%d", &n);
printf("%d\n", Solve(n));
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex58] 진약수의 개수
문제 설명
2개의 정수 N, M을 입력 받아 N부터 M까지 차례로 증가하면서 각 정수들의 진약수를 구하여 진약수의 개수가 가장 많은 정수를 찾아 인쇄한다.
진약수란 자신을 제외한 약수들을 말한다.
예로 6의 약수는 1, 2, 3, 6인데 자신을 제외한 진약수는 1, 2, 3인 3개이다.
단 함수를 설계하여 구현 한다.
#include <stdio.h>
int Solve(int n, int m)
{
//여기서 부터 작성
}
int main(void)
{
int N, M;
scanf("%d %d", &N, &M);
printf("%d\n", Solve(N, M));
return 0;
}
입력 설명
순서대로 N과 M을 입력 받는다 ( 1≦ N, M ≦ 10,000 )
출력 설명
N부터 M까지 수중에서 진약수의 개수가 가장 많은 정수를 출력한다. 동일한 값이 여러 개일 경우 가장 작은 값을 출력한다.
입력 예시
1 10
출력 예시
6
정답 코드
#include <stdio.h>
int Solve(int n, int m)
{
int num = 0, maxv = 0;
for (int i = n; i <= m; i++)
{
int cnt = 0;
for (int j = 1; j < i; j++)
{
if (i%j == 0) cnt++;
}
if (cnt > maxv)
{
maxv = cnt;
num = i;
}
}
return num;
}
int main(void)
{
int N, M;
scanf("%d %d", &N, &M);
printf("%d\n", Solve(N, M));
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex55] 원하는 자리값 알아내기
문제 설명
첫 줄에 양의 정수 하나(n)를 입력받는다.
다음 줄에 추출하고 싶은 자리 번호(d)를 하나 입력 받는다.
단, 항상 d는 n의 자리수보다 작은 값이다.
입력받은 n의 d번째 자리의 값을 인쇄하는 코드를 설계하라.
d가 0이면 1의 자리, d가 1이면 10의 자리, d가 2이면 100의 자리를 추출하면 된다.
#include <stdio.h>
int Solve(int n, int d)
{
//여기서 부터 작성
}
int main(void)
{
int n, d;
scanf("%d", &n);
scanf("%d", &d);
printf("%d\n", Solve(n, d));
return 0;
}
입력 예시
7825612
2
출력 예시
6
정답 코드
#include <stdio.h>
int pow(int x)
{
int r = 1;
for (int i = 0; i < x; i++)
{
r *= 10;
}
return r;
}
int Solve(int n, int d)
{
return n / pow(d) % 10;
}
int main(void)
{
int n, d;
scanf("%d", &n);
scanf("%d", &d);
printf("%d\n", Solve(n, d));
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex54] 중간값 찾기
문제 설명
두 수의 중간 값을 찾는 함수를 설계하라
정수 2개를 입력 받아 두 수의 중간 값을 리턴하는 함수를 설계한다
scanf로 입력 받으며 음의 정수나 양의 정수나 모두 가능하다
또한 입력된 2개의 정수는 앞에 것과 뒤의 것 중 어느 것이 큰지는 확신할 수 없다
1과 6이 입력되면 중간 값이 3, 4가 다 가능하므로 이러한 값들은 입력되지 않는다
또한, 두 값이 같은 값이 입력되는 경우도 없는 것으로 한다
#include <stdio.h>
void main(void)
{
// 코드 작성
}
입력 예시
10 20
출력 예시
15
정답 코드
#include <stdio.h>
int Search_Middle(int num1, int num2)
{
for(; num1 != num2; num1++, num2--);
return num1;
}
void main(void)
{
int min = 0, max = 0, temp;
scanf("%d %d", &min, &max);
if (min > max)
{
temp = min;
min = max;
max = temp;
}
printf("%d\n", Search_Middle(min, max));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
[ex39] 3,6,9 게임
문제 설명
다음에서 요구하는 3,6,9 게임 프로그램을 설계하라
정수 N을 scanf로 입력 받아서 1부터 N까지 다음과 같이 인쇄하라
3의 배수와 숫자에 3이 들어가는 경우는 모두 값 대신 %를 인쇄한다
3, 6, 9, 12, 13, … 23 등은 모두 숫자대신 %를 인쇄한다
N에 도달하면 N대신 “SUCCESS”를 인쇄하라
#include <stdio.h>
void main(void)
{
// 코드 작성
}
입력 설명
N <= 99
입력 예시
12
출력 예시
1
2
%
4
5
%
7
8
%
10
11
SUCCESS
정답 코드
#include <stdio.h>
void main(void)
{
int i, N;
scanf("%d", &N);
for (i = 1; i < N; i++)
{
if (((i % 3) == 0) || ((i % 10) == 3) || ((i / 10) == 3))
{
printf("%%\n");
}
else
{
printf("%d\n", i);
}
}
printf("SUCCESS\n");
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
-
[ex32] 케이크 자르기
문제 설명
아래와 같이 둥근 케이크를 2번의 칼질로 4조각으로 나누려고 한다.
케이크의 둘레에 시계방향으로 1~100까지 일정한 간격으로 번호가 부여되어 있다.
칼로 자르려고 하는 부분은 2개의 정수로 표현한다. 칼로 자르려는 부분이 2군데 주어질 때 칼로 잘리는 부분이 교차하는지 유무를 판단하는 프로그램을 작성하시오.
아래 예는 12 53과 99 45를 자른 예를 나타낸다.
#include <stdio.h>
int Solve(int A, int B, int C, int D)
{
// 여기서부터 작성
}
int main(void)
{
int a, b, c, d, cross;
// 입력받는 부분
scanf("%d %d", &a, &b);
scanf("%d %d", &c, &d);
cross = Solve(a, b, c, d);
// 출력하는 부분
if (cross == 1) printf("cross");
else printf("not cross");
return 0;
}
입력 설명
첫 번째 줄에는 첫 번째 현의 정보를 나타내는 두 정수가 입력된다.
두 번째 줄에는 두 번째 현의 정보를 나타내는 두 정수가 입력된다.
출력 설명
주어진 두 잘린 부분이 교차한다면 "cross", 교차하지 않는다면 "not cross"를 출력한다.
입력 예시
12 53
99 45
출력 예시
cross
부가정보
[입력 예시 2]
23 77
79 83
[출력 예시 2]
not cross
정답 코드
#include <stdio.h>
int Solve(int A, int B, int C, int D)
{
if (A > B)
{
int tmp = A;
A = B;
B = tmp;
}
if (C > D)
{
int tmp = C;
C = D;
D = tmp;
}
if (((A > C) && (D > A) && (D < B)) || ((A < C) && (B > C) && (B < D)))
{
return 1;
}
return 0;
}
int main(void)
{
int a, b, c, d, cross;
// 입력받는 부분
scanf("%d %d", &a, &b);
scanf("%d %d", &c, &d);
cross = Solve(a, b, c, d);
// 출력하는 부분
if (cross == 1) printf("cross");
else printf("not cross");
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex31] 시간차 구하기
문제 설명
HH:MM:SS(시:분:초)의 형태로 표시하는 2개의 시간이 주어졌을 때, 시간차를 구하는 프로그램을 작성한다.
2개의 시간은 최대 24시간 차이가 난다고 가정한다.
#include <stdio.h>
int main(void)
{
int h1, m1, s1, h2, m2, s2;
int h, m, s;
// 입력받는 부분
scanf("%d:%d:%d", &h1, &m1, &s1);
scanf("%d:%d:%d", &h2, &m2, &s2);
// 여기서부터 작성
// 출력하는 부분
printf("%02d:%02d:%02d", h, m, s);
return 0;
}
입력 설명
입력은 두 개의 시간이 입력된다. 시간이 입력되는 형태는 다음과 같다. "HH:MM:SS"
HH는 시, MM은 분, SS는 초를 뜻한다. 만약 시나 분, 초가 한 자리 숫자일 경우 앞에 0을 붙이게 된다.
(0≤HH≤23, 0≤MM, SS≤59)
앞에 입력된 시간보다 뒤의 입력된 시간이 더 늦은 시간이라고 가정한다
출력 설명
입력된 2개의 시간에 대한 시간차를 HH:MM:SS의 형태로 출력한다.
입력 예시
20:00:00
04:00:00
출력 예시
08:00:00
정답 코드
#include <stdio.h>
int main(void)
{
int h1, m1, s1, h2, m2, s2;
int h, m, s;
int ss, es;
// 입력받는 부분
scanf("%d:%d:%d", &h1, &m1, &s1);
scanf("%d:%d:%d", &h2, &m2, &s2);
// 여기서부터 작성
ss = (h1 * 60 + m1) * 60 + s1;
es = (h2 * 60 + m2) * 60 + s2;
if (es > ss) ss = es - ss;
else ss = 3600 * 24 - ss + es;
h = ss / (60 * 60);
m = ss % (60 * 60) / 60;
s = ss % 60;
// 출력하는 부분
printf("%02d:%02d:%02d", h, m, s);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex30] 두 수의 거리
문제 설명
두 정수를 입력 받아, 두 수의 차이를 절대값으로 인쇄하라.
#include <stdio.h>
int Solve(int A, int B)
{
//여기서 부터 작성
}
int main(void)
{
int A, B;
int sol;
scanf("%d %d", &A, &B);
sol = Solve(A, B);
printf("%d\n", sol);
return 0;
}
입력 설명
공백으로 구분하여 두 정수를 입력한다.
출력 설명
두 수의 차이를 절대값으로 출력한다.
입력 예시
15 12
출력 예시
3
정답 코드
#include <stdio.h>
int Solve(int A, int B)
{
//여기서 부터 작성
int diff;
if (A > B)
{
diff = A - B;
}
else
{
diff = B - A;
}
return diff;
}
int main(void)
{
int A, B;
int sol;
scanf("%d %d", &A, &B);
sol = Solve(A, B);
printf("%d\n", sol);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex29] 성적 계산 함수
문제 설명
다음과 같은 조건을 만족하는 성적처리 함수를 설계하라
함수명은 임의로 정하고 parameter는 int이고 return은 char로 지정한다
성적 기준은 다음과 같다
100~91 => A, 90~81 => B, 80~71 => C, 70~61 => D, 60이하 => F
성적을 입력하면 학점을 리턴 한다 (문자 A,B,C,D,F 중 하나)
단, 입력된 값이 0 ~ 100을 벗어나면 문자 ‘X’를 리턴 한다
#include <stdio.h>
char func(int score)
{
// 코드 작성
}
void main(void)
{
int score;
scanf("%d", &score);
printf("%c\n", func(score));
}
입력 예시
90
출력 예시
B
정답 코드
#include <stdio.h>
/*
char func(int s)
{
if ((s < 0) || (s > 100))
{
return 'X';
}
switch ((s - 1) / 10)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5: return 'F';
case 6: return 'D';
case 7: return 'C';
case 8: return 'B';
case 9:
case 10: return 'A';
}
}
*/
char func(int s)
{
char * r = "FFFFFFDCBAA";
if ((s < 0) || (s > 100))
{
return 'X';
}
return r[(s -1) / 10];
}
void main(void)
{
int score;
scanf("%d", &score);
printf("%c\n", func(score));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
-
-
-
[ex20] 2, 3, 5의 배수 판단하기
문제 설명
입력 받은 값이 2,3,5의 배수인지를 판단하는 함수를 설계하라
2의 배수면 2, 3의 배수면 3, 5의 배수면 5를 2,3,5 배수가 아니면 0을 리턴
단, 2,3 공배수면 2리턴, 3,5 공배수면 3리턴, 2,5 공배수면 2리턴, 2,3,5 공배수면 2리턴
#include <stdio.h>
int compare(int num)
{
// 코드 구현
}
void main(void)
{
int num;
scanf("%d", &num);
printf("%d\n", compare(num));
}
입력 예시
33
출력 예시
3
정답 코드
#include <stdio.h>
int compare(int num)
{
// 코드 구현
if (num % 2 == 0) return 2;
if (num % 3 == 0) return 3;
if (num % 5 == 0) return 5;
return 0;
}
void main(void)
{
int num;
scanf("%d", &num);
printf("%d\n", compare(num));
}
메모
printf 내부의 \n 습관화 필요
-
-
-
[ex17] 짝수의 개수
문제 설명
4자리 양의 정수의 각 자리수의 값이 짝수인 개수를 구하는 함수를 설계 하시오.
예를들어, 2345면 각 자리수의 값이 2, 3, 4, 5 이고 이 중에 2, 4가 짝수 이므로 2가 리턴되면 된다.
짝수는 2로 나누어 떨어지는 수이다.
#include <stdio.h>
int Solve(int A)
{
//여기서 부터 작성
}
int main(void)
{
int A;
int sol;
scanf("%d", &A);
sol = Solve(A);
printf("%d", sol);
return 0;
}
입력 설명
4자리 양의 정수가 입력
출력 설명
4자리 양의 정수의 각 자리수 값이 짝수인 개수를 출력
입력 예시
2345
출력 예시
2
정답 코드
#include <stdio.h>
int Solve(int A)
{
//여기서 부터 작성
int a, b, c, d;
int cnt = 4;
a = A / 1000;
A %= 1000;
b = A / 100;
A %= 100;
c = A / 10;
d = A % 10;
cnt -= a % 2 + b % 2 + c % 2 + d % 2;
return cnt;
}
int main(void)
{
int A;
int sol;
scanf("%d", &A);
sol = Solve(A);
printf("%d", sol);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
[ex16] 3개의 정수 중 홀수의 개수를 리턴하는 함수 설계
문제 설명
세 개의 양의 정수 A, B, C를 입력 받아 홀수의 개수를 리턴하는 함수를 설계 하시오.
세 개 모두 홀수이면 3을, 두 개면 2를, 한 개면 1을, 없으면 0을 리턴한다.
#include <stdio.h>
int Solve(int A, int B, int C)
{
int cnt = 0;
// 여기서부터 작성
return cnt;
}
int main(void)
{
int A, B, C;
int sol;
scanf("%d %d %d", &A, &B, &C);
sol = Solve(A, B, C);
printf("%d", sol);
return 0;
}
입력 설명
세 개의 양의 정수 A, B, C가 입력된다.
출력 설명
조건에 맞게 3, 2, 1, 0중 하나를 인쇄한다.
입력 예시
7 5 9
출력 예시
3
정답 코드
#include <stdio.h>
int Solve(int A, int B, int C) {
int cnt = 0;
// 여기서부터 작성
cnt = A % 2 + B % 2 + C % 2;
return cnt;
}
int main(void)
{
int A, B, C;
int sol;
scanf("%d %d %d", &A, &B, &C);
sol = Solve(A, B, C);
printf("%d", sol);
return 0;
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
-
-
[ex10] 함수의 분석 연습
문제 설명
에러가 없도록 다음 함수들을 선언하라
#include <stdio.h>
// 사용할 함수들의 선언
void main(void)
{
printf("sqr=%d\n", sqr(3));
printf("area=%d\n", area(3, 5));
printf("arc=%f\n", compute_circle_arc(4.1f));
}
int sqr(int x)
{
return x * x;
}
int area(int x, int y)
{
return x * y;
}
float compute_circle_arc(float radious)
{
float pi = 3.141592f;
radious = 2 * radious * pi;
return radious;
}
출력 예시
sqr=9
area=15
arc=25.761053
정답 코드
#include <stdio.h>
// 사용할 함수들의 선언
int sqr(int x);
int area(int x, int y);
float compute_circle_arc(float radious);
void main(void)
{
printf("sqr=%d\n", sqr(3));
printf("area=%d\n", area(3, 5));
printf("arc=%f\n", compute_circle_arc(4.1f));
}
int sqr(int x)
{
return x * x;
}
int area(int x, int y)
{
return x * y;
}
float compute_circle_arc(float radious)
{
float pi = 3.141592f;
radious = 2 * radious * pi;
return radious;
}
메모
printf 내부의 \n 습관화 필요
-
-
-
-
[ex06] 정수 3개 합과 평균 구하기
문제 설명
공백으로 분리된 정수 3개를 입력 받아 합과 평균을 인쇄하라
#include<stdio.h>
void main(void)
{
int a, b, c, sum;
float avg;
// 코드 작성
printf("%d, %f\n", sum, avg);
}
입력 예시
10 20 30
출력 예시
60, 20.000000
정답 코드
#include<stdio.h>
void main(void)
{
int a, b, c, sum;
float avg;
// 코드 작성
scanf("%d %d %d", &a, &b, &c);
sum = a + b + c;
avg = sum / 3.0f;
printf("%d, %f\n", sum, avg);
}
메모
printf 내부의 \n 습관화 필요
-
[ex05] 16진수의 자리수 분리
문제 설명
4자리 16진수 수를 입력 받아 각 자리 값을 인쇄하라
#include<stdio.h>
void main(void)
{
unsigned int x;
unsigned int x4, x3, x2, x1;
scanf("%x", &x);
// 코드 작성
printf("%X, %X, %X, %X", x4, x3, x2, x1);
}
입력 예시
AB9D
출력 예시
A, B, 9, D
정답 코드
#include<stdio.h>
void main(void)
{
unsigned int x;
unsigned int x4, x3, x2, x1;
scanf("%x", &x);
// 코드 작성
x4 = (x / (16 * 16 * 16));
x3 = ((x % (16 * 16 * 16)) / (16 * 16));
x2 = ((x % (16 * 16)) / 16);
x1 = (x % 16);
printf("%X, %X, %X, %X", x4, x3, x2, x1);
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex03] /, % 연산자의 활용 => 10진수 자리수 분리
문제 설명
4자리 정수의 각 자리 값을 추출하여 a4, a3, a2, a1에 저장하라
#include <stdio.h>
void main(void)
{
int a = 2345;
int a4, a3, a2, a1;
a4 =
a3 =
a2 =
a1 =
printf("1000자리=%d, 100자리=%d, 10자리=%d, 1자리=%d\n", a4, a3, a2, a1);
}
출력 예시
1000자리=2, 100자리=3, 10자리=4, 1자리=5
정답 코드
#include <stdio.h>
void main(void)
{
int a = 2345;
int a4, a3, a2, a1;
// 1의 자리부터 코딩
a4 = (a / 1000);
a3 = (a / 100) % 10;
a2 = (a / 10) % 10;
a1 = a % 10;
printf("1000자리=%d, 100자리=%d, 10자리=%d, 1자리=%d\n", a4, a3, a2, a1);
}
메모
printf 내부의 \n 습관화 필요
-
[ex02] 다양한 입력 및 출력 연습
문제 설명
다음 코드에 들어갈 입력 및 인쇄 코드를 설계하라
입력 예시와 같이 입력 시 출력 예시와 같이 인쇄가 되어야 한다
[주의] printf 사용시 출력 예시와 완전히 동일하도록 공백, ‘,’ 등의 인쇄에 주의하여야 한다
#include <stdio.h>
void main(void)
{
char name[31];
int age;
float height;
char blood_type;
char nationality[11];
// 코드 작성
}
입력 예시
Hong Gil Dong
100
182.9
A
KOR
출력 예시
Hong Gil Dong, 100, 182.899994
A, KOR
정답 코드
#include <stdio.h>
void main(void)
{
char name[31];
int age;
float height;
char blood_type;
char nationality[11];
// 코드 작성
gets(name);
scanf("%d %f %c %s", &age, &height, &blood_type, nationality);
printf("%s, %d, %f\n", name, age, height);
printf("%c, %s", blood_type, nationality);
}
메모
printf 내부의 \n 습관화 필요
-
-
[ex01] 포인터 배열
문제 설명
배열 a를 이용하여 x[2]를 30으로 만드는 코드를 만드시오
#include <stdio.h>
int x[4] = {1,2,3,4};
void main(void)
{
int *a[4] = {x+3, x+2, x+1, x};
printf("%d\n", x[2]);
= 30;
printf("%d\n", x[2]);
}
출력 예시
3
30
정답
#include <stdio.h>
int x[4] = {1,2,3,4};
void main(void)
{
int *a[4] = {x+3, x+2, x+1, x};
printf("%d\n", x[2]);
//a[0][-1] = 30;
//a[1][0] = 30;
//a[2][1] = 30;
a[3][2] = 30;
printf("%d\n", x[2]);
}
메모
printf 내부의 \n 습관화 필요
-
-
Manage blog comments with Giscus
Giscus is a free comments system powered without your own database. Giscus uses the Github Discussions to store and load associated comments based on a chosen mapping (URL, pathname, title, etc.).
To comment, visitors must authorize the giscus app to post on their behalf using the GitHub OAuth flow. Alternatively, visitors can comment on the GitHub Discussion directly. You can moderate the comments on GitHub.
Prerequisites
Create a github repo
You need a GitHub repository first. If you gonna use GitHub Pages for hosting your website, you can choose the corresponding repository (i.e., [userID].github.io)
The repository should be public, otherwise visitors will not be able to view the discussion.
Turn on Discussion feature
In your GitHub repository Settings, make sure that General > Features > Discussions feature is enabled.
Activate Giscus API
Follow the steps in Configuration guide. Make sure the verification of your repository is successful.
Then, scroll down from the manual page and choose the Discussion Category options. You don’t need to touch other configs.
Copy _config.yml
Now, you get the giscus script. Copy the four properties marked with a red box as shown below:
Paste those values to _config.yml placed in the root directory.
# External API
giscus_repo: "[ENTER REPO HERE]"
giscus_repoId: "[ENTER REPO ID HERE]"
giscus_category: "[ENTER CATEGORY NAME HERE]"
giscus_categoryId: "[ENTER CATEGORY ID HERE]"
None
· 2024-02-03
-
-
Classic Literature #2: Don Quixote
About the book
Author: Miguel de Cervantes
Original title: El ingenioso hidalgo don Quixote de la Mancha
Country: Spain
Genre: Novel
Publication date:
1605 (Part One)
1615 (Part Two)
Chapter I.
In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income. The rest of it went in a doublet of fine cloth and velvet breeches and shoes to match for holidays, while on week-days he made a brave figure in his best homespun. He had in his house a housekeeper past forty, a niece under twenty, and a lad for the field and market-place, who used to saddle the hack as well as handle the bill-hook. The age of this gentleman of ours was bordering on fifty; he was of a hardy habit, spare, gaunt-featured, a very early riser and a great sportsman. They will have it his surname was Quixada or Quesada (for here there is some difference of opinion among the authors who write on the subject), although from reasonable conjectures it seems plain that he was called Quexana. This, however, is of but little importance to our tale; it will be enough not to stray a hair’s breadth from the truth in the telling of it.
You must know, then, that the above-named gentleman whenever he was at leisure (which was mostly all the year round) gave himself up to reading books of chivalry with such ardour and avidity that he almost entirely neglected the pursuit of his field-sports, and even the management of his property; and to such a pitch did his eagerness and infatuation go that he sold many an acre of tillageland to buy books of chivalry to read, and brought home as many of them as he could get. But of all there were none he liked so well as those of the famous Feliciano de Silva’s composition, for their lucidity of style and complicated conceits were as pearls in his sight, particularly when in his reading he came upon courtships and cartels, where he often found passages like “the reason of the unreason with which my reason is afflicted so weakens my reason that with reason I murmur at your beauty;” or again, “the high heavens, that of your divinity divinely fortify you with the stars, render you deserving of the desert your greatness deserves.” Over conceits of this sort the poor gentleman lost his wits, and used to lie awake striving to understand them and worm the meaning out of them; what Aristotle himself could not have made out or extracted had he come to life again for that special purpose. He was not at all easy about the wounds which Don Belianis gave and took, because it seemed to him that, great as were the surgeons who had cured him, he must have had his face and body covered all over with seams and scars. He commended, however, the author’s way of ending his book with the promise of that interminable adventure, and many a time was he tempted to take up his pen and finish it properly as is there proposed, which no doubt he would have done, and made a successful piece of work of it too, had not greater and more absorbing thoughts prevented him.
Many an argument did he have with the curate of his village (a learned man, and a graduate of Siguenza) as to which had been the better knight, Palmerin of England or Amadis of Gaul. Master Nicholas, the village barber, however, used to say that neither of them came up to the Knight of Phoebus, and that if there was any that could compare with him it was Don Galaor, the brother of Amadis of Gaul, because he had a spirit that was equal to every occasion, and was no finikin knight, nor lachrymose like his brother, while in the matter of valour he was not a whit behind him. In short, he became so absorbed in his books that he spent his nights from sunset to sunrise, and his days from dawn to dark, poring over them; and what with little sleep and much reading his brains got so dry that he lost his wits. His fancy grew full of what he used to read about in his books, enchantments, quarrels, battles, challenges, wounds, wooings, loves, agonies, and all sorts of impossible nonsense; and it so possessed his mind that the whole fabric of invention and fancy he read of was true, that to him no history in the world had more reality in it. He used to say the Cid Ruy Diaz was a very good knight, but that he was not to be compared with the Knight of the Burning Sword who with one back-stroke cut in half two fierce and monstrous giants. He thought more of Bernardo del Carpio because at Roncesvalles he slew Roland in spite of enchantments, availing himself of the artifice of Hercules when he strangled Antaeus the son of Terra in his arms. He approved highly of the giant Morgante, because, although of the giant breed which is always arrogant and ill-conditioned, he alone was affable and well-bred. But above all he admired Reinaldos of Montalban, especially when he saw him sallying forth from his castle and robbing everyone he met, and when beyond the seas he stole that image of Mahomet which, as his history says, was entirely of gold. To have a bout of kicking at that traitor of a Ganelon he would have given his housekeeper, and his niece into the bargain.
In short, his wits being quite gone, he hit upon the strangest notion that ever madman in this world hit upon, and that was that he fancied it was right and requisite, as well for the support of his own honour as for the service of his country, that he should make a knight-errant of himself, roaming the world over in full armour and on horseback in quest of adventures, and putting in practice himself all that he had read of as being the usual practices of knights-errant; righting every kind of wrong, and exposing himself to peril and danger from which, in the issue, he was to reap eternal renown and fame. Already the poor man saw himself crowned by the might of his arm Emperor of Trebizond at least; and so, led away by the intense enjoyment he found in these pleasant fancies, he set himself forthwith to put his scheme into execution.
The first thing he did was to clean up some armour that had belonged to his great-grandfather, and had been for ages lying forgotten in a corner eaten with rust and covered with mildew. He scoured and polished it as best he could, but he perceived one great defect in it, that it had no closed helmet, nothing but a simple morion. This deficiency, however, his ingenuity supplied, for he contrived a kind of half-helmet of pasteboard which, fitted on to the morion, looked like a whole one. It is true that, in order to see if it was strong and fit to stand a cut, he drew his sword and gave it a couple of slashes, the first of which undid in an instant what had taken him a week to do. The ease with which he had knocked it to pieces disconcerted him somewhat, and to guard against that danger he set to work again, fixing bars of iron on the inside until he was satisfied with its strength; and then, not caring to try any more experiments with it, he passed it and adopted it as a helmet of the most perfect construction.
He next proceeded to inspect his hack, which, with more quartos than a real and more blemishes than the steed of Gonela, that “tantum pellis et ossa fuit,” surpassed in his eyes the Bucephalus of Alexander or the Babieca of the Cid. Four days were spent in thinking what name to give him, because (as he said to himself) it was not right that a horse belonging to a knight so famous, and one with such merits of his own, should be without some distinctive name, and he strove to adapt it so as to indicate what he had been before belonging to a knight-errant, and what he then was; for it was only reasonable that, his master taking a new character, he should take a new name, and that it should be a distinguished and full-sounding one, befitting the new order and calling he was about to follow. And so, after having composed, struck out, rejected, added to, unmade, and remade a multitude of names out of his memory and fancy, he decided upon calling him Rocinante, a name, to his thinking, lofty, sonorous, and significant of his condition as a hack before he became what he now was, the first and foremost of all the hacks in the world.
Having got a name for his horse so much to his taste, he was anxious to get one for himself, and he was eight days more pondering over this point, till at last he made up his mind to call himself “Don Quixote,” whence, as has been already said, the authors of this veracious history have inferred that his name must have been beyond a doubt Quixada, and not Quesada as others would have it. Recollecting, however, that the valiant Amadis was not content to call himself curtly Amadis and nothing more, but added the name of his kingdom and country to make it famous, and called himself Amadis of Gaul, he, like a good knight, resolved to add on the name of his, and to style himself Don Quixote of La Mancha, whereby, he considered, he described accurately his origin and country, and did honour to it in taking his surname from it.
So then, his armour being furbished, his morion turned into a helmet, his hack christened, and he himself confirmed, he came to the conclusion that nothing more was needed now but to look out for a lady to be in love with; for a knight-errant without love was like a tree without leaves or fruit, or a body without a soul. As he said to himself, “If, for my sins, or by my good fortune, I come across some giant hereabouts, a common occurrence with knights-errant, and overthrow him in one onslaught, or cleave him asunder to the waist, or, in short, vanquish and subdue him, will it not be well to have some one I may send him to as a present, that he may come in and fall on his knees before my sweet lady, and in a humble, submissive voice say, ‘I am the giant Caraculiambro, lord of the island of Malindrania, vanquished in single combat by the never sufficiently extolled knight Don Quixote of La Mancha, who has commanded me to present myself before your Grace, that your Highness dispose of me at your pleasure’?” Oh, how our good gentleman enjoyed the delivery of this speech, especially when he had thought of some one to call his Lady! There was, so the story goes, in a village near his own a very good-looking farm-girl with whom he had been at one time in love, though, so far as is known, she never knew it nor gave a thought to the matter. Her name was Aldonza Lorenzo, and upon her he thought fit to confer the title of Lady of his Thoughts; and after some search for a name which should not be out of harmony with her own, and should suggest and indicate that of a princess and great lady, he decided upon calling her Dulcinea del Toboso—she being of El Toboso—a name, to his mind, musical, uncommon, and significant, like all those he had already bestowed upon himself and the things belonging to him.
-
Classic Literature #2: Don Quixote
About the book
Author: Miguel de Cervantes
Original title: El ingenioso hidalgo don Quixote de la Mancha
Country: Spain
Genre: Novel
Publication date:
1605 (Part One)
1615 (Part Two)
Chapter I.
In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income. The rest of it went in a doublet of fine cloth and velvet breeches and shoes to match for holidays, while on week-days he made a brave figure in his best homespun. He had in his house a housekeeper past forty, a niece under twenty, and a lad for the field and market-place, who used to saddle the hack as well as handle the bill-hook. The age of this gentleman of ours was bordering on fifty; he was of a hardy habit, spare, gaunt-featured, a very early riser and a great sportsman. They will have it his surname was Quixada or Quesada (for here there is some difference of opinion among the authors who write on the subject), although from reasonable conjectures it seems plain that he was called Quexana. This, however, is of but little importance to our tale; it will be enough not to stray a hair’s breadth from the truth in the telling of it.
You must know, then, that the above-named gentleman whenever he was at leisure (which was mostly all the year round) gave himself up to reading books of chivalry with such ardour and avidity that he almost entirely neglected the pursuit of his field-sports, and even the management of his property; and to such a pitch did his eagerness and infatuation go that he sold many an acre of tillageland to buy books of chivalry to read, and brought home as many of them as he could get. But of all there were none he liked so well as those of the famous Feliciano de Silva’s composition, for their lucidity of style and complicated conceits were as pearls in his sight, particularly when in his reading he came upon courtships and cartels, where he often found passages like “the reason of the unreason with which my reason is afflicted so weakens my reason that with reason I murmur at your beauty;” or again, “the high heavens, that of your divinity divinely fortify you with the stars, render you deserving of the desert your greatness deserves.” Over conceits of this sort the poor gentleman lost his wits, and used to lie awake striving to understand them and worm the meaning out of them; what Aristotle himself could not have made out or extracted had he come to life again for that special purpose. He was not at all easy about the wounds which Don Belianis gave and took, because it seemed to him that, great as were the surgeons who had cured him, he must have had his face and body covered all over with seams and scars. He commended, however, the author’s way of ending his book with the promise of that interminable adventure, and many a time was he tempted to take up his pen and finish it properly as is there proposed, which no doubt he would have done, and made a successful piece of work of it too, had not greater and more absorbing thoughts prevented him.
Many an argument did he have with the curate of his village (a learned man, and a graduate of Siguenza) as to which had been the better knight, Palmerin of England or Amadis of Gaul. Master Nicholas, the village barber, however, used to say that neither of them came up to the Knight of Phoebus, and that if there was any that could compare with him it was Don Galaor, the brother of Amadis of Gaul, because he had a spirit that was equal to every occasion, and was no finikin knight, nor lachrymose like his brother, while in the matter of valour he was not a whit behind him. In short, he became so absorbed in his books that he spent his nights from sunset to sunrise, and his days from dawn to dark, poring over them; and what with little sleep and much reading his brains got so dry that he lost his wits. His fancy grew full of what he used to read about in his books, enchantments, quarrels, battles, challenges, wounds, wooings, loves, agonies, and all sorts of impossible nonsense; and it so possessed his mind that the whole fabric of invention and fancy he read of was true, that to him no history in the world had more reality in it. He used to say the Cid Ruy Diaz was a very good knight, but that he was not to be compared with the Knight of the Burning Sword who with one back-stroke cut in half two fierce and monstrous giants. He thought more of Bernardo del Carpio because at Roncesvalles he slew Roland in spite of enchantments, availing himself of the artifice of Hercules when he strangled Antaeus the son of Terra in his arms. He approved highly of the giant Morgante, because, although of the giant breed which is always arrogant and ill-conditioned, he alone was affable and well-bred. But above all he admired Reinaldos of Montalban, especially when he saw him sallying forth from his castle and robbing everyone he met, and when beyond the seas he stole that image of Mahomet which, as his history says, was entirely of gold. To have a bout of kicking at that traitor of a Ganelon he would have given his housekeeper, and his niece into the bargain.
In short, his wits being quite gone, he hit upon the strangest notion that ever madman in this world hit upon, and that was that he fancied it was right and requisite, as well for the support of his own honour as for the service of his country, that he should make a knight-errant of himself, roaming the world over in full armour and on horseback in quest of adventures, and putting in practice himself all that he had read of as being the usual practices of knights-errant; righting every kind of wrong, and exposing himself to peril and danger from which, in the issue, he was to reap eternal renown and fame. Already the poor man saw himself crowned by the might of his arm Emperor of Trebizond at least; and so, led away by the intense enjoyment he found in these pleasant fancies, he set himself forthwith to put his scheme into execution.
The first thing he did was to clean up some armour that had belonged to his great-grandfather, and had been for ages lying forgotten in a corner eaten with rust and covered with mildew. He scoured and polished it as best he could, but he perceived one great defect in it, that it had no closed helmet, nothing but a simple morion. This deficiency, however, his ingenuity supplied, for he contrived a kind of half-helmet of pasteboard which, fitted on to the morion, looked like a whole one. It is true that, in order to see if it was strong and fit to stand a cut, he drew his sword and gave it a couple of slashes, the first of which undid in an instant what had taken him a week to do. The ease with which he had knocked it to pieces disconcerted him somewhat, and to guard against that danger he set to work again, fixing bars of iron on the inside until he was satisfied with its strength; and then, not caring to try any more experiments with it, he passed it and adopted it as a helmet of the most perfect construction.
He next proceeded to inspect his hack, which, with more quartos than a real and more blemishes than the steed of Gonela, that “tantum pellis et ossa fuit,” surpassed in his eyes the Bucephalus of Alexander or the Babieca of the Cid. Four days were spent in thinking what name to give him, because (as he said to himself) it was not right that a horse belonging to a knight so famous, and one with such merits of his own, should be without some distinctive name, and he strove to adapt it so as to indicate what he had been before belonging to a knight-errant, and what he then was; for it was only reasonable that, his master taking a new character, he should take a new name, and that it should be a distinguished and full-sounding one, befitting the new order and calling he was about to follow. And so, after having composed, struck out, rejected, added to, unmade, and remade a multitude of names out of his memory and fancy, he decided upon calling him Rocinante, a name, to his thinking, lofty, sonorous, and significant of his condition as a hack before he became what he now was, the first and foremost of all the hacks in the world.
Having got a name for his horse so much to his taste, he was anxious to get one for himself, and he was eight days more pondering over this point, till at last he made up his mind to call himself “Don Quixote,” whence, as has been already said, the authors of this veracious history have inferred that his name must have been beyond a doubt Quixada, and not Quesada as others would have it. Recollecting, however, that the valiant Amadis was not content to call himself curtly Amadis and nothing more, but added the name of his kingdom and country to make it famous, and called himself Amadis of Gaul, he, like a good knight, resolved to add on the name of his, and to style himself Don Quixote of La Mancha, whereby, he considered, he described accurately his origin and country, and did honour to it in taking his surname from it.
So then, his armour being furbished, his morion turned into a helmet, his hack christened, and he himself confirmed, he came to the conclusion that nothing more was needed now but to look out for a lady to be in love with; for a knight-errant without love was like a tree without leaves or fruit, or a body without a soul. As he said to himself, “If, for my sins, or by my good fortune, I come across some giant hereabouts, a common occurrence with knights-errant, and overthrow him in one onslaught, or cleave him asunder to the waist, or, in short, vanquish and subdue him, will it not be well to have some one I may send him to as a present, that he may come in and fall on his knees before my sweet lady, and in a humble, submissive voice say, ‘I am the giant Caraculiambro, lord of the island of Malindrania, vanquished in single combat by the never sufficiently extolled knight Don Quixote of La Mancha, who has commanded me to present myself before your Grace, that your Highness dispose of me at your pleasure’?” Oh, how our good gentleman enjoyed the delivery of this speech, especially when he had thought of some one to call his Lady! There was, so the story goes, in a village near his own a very good-looking farm-girl with whom he had been at one time in love, though, so far as is known, she never knew it nor gave a thought to the matter. Her name was Aldonza Lorenzo, and upon her he thought fit to confer the title of Lady of his Thoughts; and after some search for a name which should not be out of harmony with her own, and should suggest and indicate that of a princess and great lady, he decided upon calling her Dulcinea del Toboso—she being of El Toboso—a name, to his mind, musical, uncommon, and significant, like all those he had already bestowed upon himself and the things belonging to him.
-
Classic Literature #1: Romeo and Juliet
About the book
Author: William Shakespeare
Country: England
Genre: Shakespearean tragedy
Publication date: 1597
Synopsis
The prologue of Romeo and Juliet calls the title characters “star-crossed lovers”—and the stars do seem to conspire against these young lovers.
Romeo is a Montague, and Juliet a Capulet. Their families are enmeshed in a feud, but the moment they meet—when Romeo and his friends attend a party at Juliet’s house in disguise—the two fall in love and quickly decide that they want to be married.
A friar secretly marries them, hoping to end the feud. Romeo and his companions almost immediately encounter Juliet’s cousin Tybalt, who challenges Romeo. When Romeo refuses to fight, Romeo’s friend Mercutio accepts the challenge and is killed. Romeo then kills Tybalt and is banished. He spends that night with Juliet and then leaves for Mantua.
Juliet’s father forces her into a marriage with Count Paris. To avoid this marriage, Juliet takes a potion, given her by the friar, that makes her appear dead. The friar will send Romeo word to be at her family tomb when she awakes. The plan goes awry, and Romeo learns instead that she is dead. In the tomb, Romeo kills himself. Juliet wakes, sees his body, and commits suicide. Their deaths appear finally to end the feud.
-
Classic Literature #1: Romeo and Juliet
About the book
Author: William Shakespeare
Country: England
Genre: Shakespearean tragedy
Publication date: 1597
Synopsis
The prologue of Romeo and Juliet calls the title characters “star-crossed lovers”—and the stars do seem to conspire against these young lovers.
Romeo is a Montague, and Juliet a Capulet. Their families are enmeshed in a feud, but the moment they meet—when Romeo and his friends attend a party at Juliet’s house in disguise—the two fall in love and quickly decide that they want to be married.
A friar secretly marries them, hoping to end the feud. Romeo and his companions almost immediately encounter Juliet’s cousin Tybalt, who challenges Romeo. When Romeo refuses to fight, Romeo’s friend Mercutio accepts the challenge and is killed. Romeo then kills Tybalt and is banished. He spends that night with Juliet and then leaves for Mantua.
Juliet’s father forces her into a marriage with Count Paris. To avoid this marriage, Juliet takes a potion, given her by the friar, that makes her appear dead. The friar will send Romeo word to be at her family tomb when she awakes. The plan goes awry, and Romeo learns instead that she is dead. In the tomb, Romeo kills himself. Juliet wakes, sees his body, and commits suicide. Their deaths appear finally to end the feud.
-
My personal Online Library
What is Lorem Ipsum?
This is an example post ‘<’. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ‘Content here, content here’, making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ‘lorem ipsum’ will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of “de Finibus Bonorum et Malorum” (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, “Lorem ipsum dolor sit amet..”, comes from a line in section 1.10.32.
The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from “de Finibus Bonorum et Malorum” by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
Where can I get some?
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don’t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn’t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
-
-
-
Markdown from A to Z
Headings
To create a heading, add number signs (#) in front of a word or phrase. The number of number signs you use should correspond to the heading level. For example, to create a heading level three (<h3>), use three number signs (e.g., ### My Header).
Markdown
HTML
Rendered Output
# Header 1
<h1>Header 1</h1>
Header 1
## Header 2
<h2>Header 2</h2>
Header 2
### Header 3
<h3>Header 3</h3>
Header 3
Emphasis
You can add emphasis by making text bold or italic.
Bold
To bold text, add two asterisks (e.g., **text** = text) or underscores before and after a word or phrase. To bold the middle of a word for emphasis, add two asterisks without spaces around the letters.
Italic
To italicize text, add one asterisk (e.g., *text* = text) or underscore before and after a word or phrase. To italicize the middle of a word for emphasis, add one asterisk without spaces around the letters.
Blockquotes
To create a blockquote, add a > in front of a paragraph.
> Yongha Kim is the best developer in the world.
>
> Factos 👍👀
Yongha Kim is the best developer in the world.
Factos 👍👀
Lists
You can organize items into ordered and unordered lists.
Ordered Lists
To create an ordered list, add line items with numbers followed by periods. The numbers don’t have to be in numerical order, but the list should start with the number one.
1. First item
2. Second item
3. Third item
4. Fourth item
First item
Second item
Third item
Fourth item
Unordered Lists
To create an unordered list, add dashes (-), asterisks (*), or plus signs (+) in front of line items. Indent one or more items to create a nested list.
* First item
* Second item
* Third item
* Fourth item
First item
Second item
Third item
Fourth item
Code
To denote a word or phrase as code, enclose it in backticks (`).
Markdown
HTML
Rendered Output
At the command prompt, type `nano`.
At the command prompt, type <code>nano</code>.
At the command prompt, type nano.
Escaping Backticks
If the word or phrase you want to denote as code includes one or more backticks, you can escape it by enclosing the word or phrase in double backticks (``).
Markdown
HTML
Rendered Output
``Use `code` in your Markdown file.``
<code>Use `code` in your Markdown file.</code>
Use `code` in your Markdown file.
Code Blocks
To create code blocks that spans multiple lines of code, set the text inside three or more backquotes ( ``` ) or tildes ( ~~~ ).
<html>
<head>
</head>
</html>
def foo():
a = 1
for i in [1,2,3]:
a += i
Horizontal Rules
To create a horizontal rule, use three or more asterisks (***), dashes (---), or underscores (___) on a line by themselves.
***
---
_________________
Links
To create a link, enclose the link text in brackets (e.g., [Blue Archive]) and then follow it immediately with the URL in parentheses (e.g., (https://bluearchive.nexon.com)).
My favorite mobile game is [Blue Archive](https://bluearchive.nexon.com).
The rendered output looks like this:
My favorite mobile game is Blue Archive.
Adding Titles
You can optionally add a title for a link. This will appear as a tooltip when the user hovers over the link. To add a title, enclose it in quotation marks after the URL.
My favorite mobile game is [Blue Archive](https://bluearchive.nexon.com "All senseis are welcome!").
The rendered output looks like this:
My favorite mobile game is Blue Archive.
URLs and Email Addresses
To quickly turn a URL or email address into a link, enclose it in angle brackets.
<https://www.youtube.com/>
<fake@example.com>
The rendered output looks like this:
https://www.youtube.com/
fake@example.com
Images
To add an image, add an exclamation mark (!), followed by alt text in brackets, and the path or URL to the image asset in parentheses. You can optionally add a title in quotation marks after the path or URL.

The rendered output looks like this:
Linking Images
To add a link to an image, enclose the Markdown for the image in brackets, and then add the link in parentheses.
[](https://www.britannica.com/place/La-Mancha)
The rendered output looks like this:
Escaping Characters
To display a literal character that would otherwise be used to format text in a Markdown document, add a backslash (\) in front of the character.
\* Without the backslash, this would be a bullet in an unordered list.
The rendered output looks like this:
* Without the backslash, this would be a bullet in an unordered list.
Characters You Can Escape
You can use a backslash to escape the following characters.
Character
Name
`
backtick
*
asterisk
_
underscore
{}
curly braces
[]
brackets
<>
angle brackets
()
parentheses
#
pound sign
+
plus sign
-
minus sign (hyphen)
.
dot
!
exclamation mark
|
pipe
HTML
Many Markdown applications allow you to use HTML tags in Markdown-formatted text. This is helpful if you prefer certain HTML tags to Markdown syntax. For example, some people find it easier to use HTML tags for images. Using HTML is also helpful when you need to change the attributes of an element, like specifying the color of text or changing the width of an image.
To use HTML, place the tags in the text of your Markdown-formatted file.
This **word** is bold. This <span style="font-style: italic;">word</span> is italic.
The rendered output looks like this:
This word is bold. This word is italic.
None
· 2023-09-05
Touch background to close