제어에서 가장 중요한 건 조건
시퀀스가 있기 때문에 루프가 가능함
stream manipulator boolalpha
==, !=, <, >, <=, >=&&(AND), ||(OR), !(NOT)#include <iostream>
using namespace std;
int main() {
bool b = (1 == 2); // false
cout << boolalpha; // bool 값을 true/false로 출력
cout << b << endl; // false 출력
return 0;
}
if (조건) {
// 조건이 참일 때 실행
} else {
// 조건이 거짓일 때 실행
}
// 두 수 중 큰 값 찾기
int x, y;
cin >> x >> y;
if (x > y)
cout << "x가 y보다 큽니다." << endl;
else
cout << "y가 x보다 큽니다." << endl;
if (조건1) {
// 조건1이 참
} else if (조건2) {
// 조건1은 거짓, 조건2는 참
} else {
// 모든 조건이 거짓
}
int age;
cin >> age;
if (age <= 12)
cout << "어린이입니다." << endl;
else if (age <= 19)
cout << "청소년입니다." << endl;
else
cout << "성인입니다." << endl;
switch (변수) {
case 값1:
문장1;
break;
case 값2:
문장2;
break;
default:
기본문장;
break;
}
int n = 10;
while (n > 0) {
cout << n << " ";
n--;
}
string str;
do {
cout << "문자열을 입력하시오: ";
getline(cin, str);
cout << "사용자의 입력: " << str << endl;
} while (str != "종료");
// 1부터 10까지 합계
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
cout << "합계: " << sum << endl;
for (int i = 1; i < 10; i++) {
cout << i << " ";
if (i == 4)
break; // 루프 종료
}
// 출력: 1 2 3 4
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // 3일 때 건너뛰기
cout << i << " ";
}
// 출력: 1 2 4 5
// 선언
int scores[10];
// 초기화
int sales[5] = {100, 200, 300, 400, 500};
int sales[] = {100, 200, 300}; // 크기 자동 결정
// 보편적 초기화 (C++11)
int scores[]{10, 20, 30};
int list[] = {1, 2, 3, 4, 5};
// 읽기만
for (int i : list) {
cout << i << " ";
}
// 수정 가능
for (int& i : list) {
i = i * 2; // 값 변경
}
// 자동 타입 추론
for (auto& i : list) {
cout << i << " ";
}
// 선언
int s[3][5];
// 초기화
int table[3][5] = {
{1, 2, 3, 4, 5},
{2, 4, 6, 8, 10},
{3, 6, 9, 12, 15}
};
// 이중 반복문으로 접근
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 5; c++) {
cout << table[r][c] << " ";
}
cout << endl;
}
문제: 사용자로부터 점수를 입력받아 학점을 출력하는 프로그램을 작성하시오.
해답:
#include <iostream>
using namespace std;
int main() {
int score;
cout << "점수를 입력하세요: ";
cin >> score;
if (score >= 90)
cout << "학점: A" << endl;
else if (score >= 80)
cout << "학점: B" << endl;
else if (score >= 70)
cout << "학점: C" << endl;
else if (score >= 60)
cout << "학점: D" << endl;
else
cout << "학점: F" << endl;
return 0;
}
문제: 1부터 n까지의 수 중에서 홀수만의 합을 구하는 프로그램을 작성하시오.
해답:
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "n을 입력하세요: ";
cin >> n;
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) { // 홀수일 때
sum += i;
}
}
cout << "1부터 " << n << "까지 홀수의 합: " << sum << endl;
return 0;
}
문제: 10개의 정수를 배열에 저장하고, 배열에서 최댓값과 최솟값을 찾아 출력하는 프로그램을 작성하시오.
해답:
#include <iostream>
using namespace std;
int main() {
int numbers[10];
// 배열에 값 입력
cout << "10개의 정수를 입력하세요: ";
for (int i = 0; i < 10; i++) {
cin >> numbers[i];
}
// 최댓값과 최솟값 찾기
int max = numbers[0];
int min = numbers[0];
for (int i = 1; i < 10; i++) {
if (numbers[i] > max)
max = numbers[i];
if (numbers[i] < min)
min = numbers[i];
}
cout << "최댓값: " << max << endl;
cout << "최솟값: " << min << endl;
return 0;
}
문제: 3×3 행렬의 각 행의 합을 구하는 프로그램을 작성하시오.
해답:
#include <iostream>
using namespace std;
int main() {
int matrix[3][3];
// 행렬 입력
cout << "3x3 행렬을 입력하세요:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> matrix[i][j];
}
}
// 각 행의 합 계산
for (int i = 0; i < 3; i++) {
int rowSum = 0;
for (int j = 0; j < 3; j++) {
rowSum += matrix[i][j];
}
cout << "행 " << (i+1) << "의 합: " << rowSum << endl;
}
return 0;
}
문제: 학생 5명의 3과목 점수를 2차원 배열에 저장하고, 각 학생의 평균과 전체 평균을 구하는 프로그램을 작성하시오.
해답:
#include <iostream>
using namespace std;
int main() {
int scores[5][3]; // 5명의 학생, 3과목
// 점수 입력
for (int i = 0; i < 5; i++) {
cout << "학생 " << (i+1) << "의 3과목 점수를 입력하세요: ";
for (int j = 0; j < 3; j++) {
cin >> scores[i][j];
}
}
int totalSum = 0;
// 각 학생의 평균 계산
for (int i = 0; i < 5; i++) {
int studentSum = 0;
for (int j = 0; j < 3; j++) {
studentSum += scores[i][j];
}
totalSum += studentSum;
double average = studentSum / 3.0;
cout << "학생 " << (i+1) << "의 평균: " << average << endl;
}
// 전체 평균
double totalAverage = totalSum / 15.0; // 5명 × 3과목 = 15
cout << "전체 평균: " << totalAverage << endl;
return 0;
}
int& 사용문제: 다음 코드의 출력 결과를 예측하시오.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
if (i % 2 == 0)
continue;
cout << arr[i] << " ";
}
cout << endl;
for (auto& x : arr) {
x *= 2;
}
for (int x : arr) {
cout << x << " ";
}
return 0;
}
정답:
2 4
2 4 6 8 10
해설: