기본 자료형, 입출력
#include <iostream> // 헤더 포함할때 사용 #include <헤더명>
using namespace std; // 네임스페이스 적용시 사용 using namespace 이름;
int main() {
// 기본 자료형은 값이 할당되기 전에 쓰레기값이 들어있음
int i = 0; // 정수형 변수
float f = 0.0; // 실수형 변수
double d = 0.0; // 실수형 변수
bool b = true; // 불린형 변수
string hi = "Hello"; // string 변수. char의 연속된 값
string answer;
char first = '@'; // char 변수
int *pi = &i; // 포인터 변수
cout << greeting << "World!!"; // 출력할 땐 cout << 값
cin >> answer; // 입력할 땐 cin >> 값
cout << pi; // i의 주소값
cout << π // pi의 주소값
return 0;
}
조건문
#includue <iostream>
using namespace std;
int main() {
int x = 1;
int y = 2;
// 기본 if 문
if (x < y)
{
cout << y; // x < y 일 경우 y 출력
}
else if (x == y) // x == y 일 경우 equal 출력
{
cout << "equal";
}
else // 둘다 아니라면 x 출력
{
cout << x;
}
// 삼항 연산
cout << (x < y) ? "X" : "Y"; // (조건문) ? 참일경우 : 거짓일경우
// switch 문
switch (x) // x 값에 따라 결과값이 바뀜
{
case 1: // x가 1일때
cout << "X";
break;
case 2: // x가 2일때
cout << "Y";
break;
default: // 모두 아닐경우
cout << "Z";
}
}
반복문
#include <iostream>
using namespace std;
int main() {
// while문. 주어진 조건이 있을경우 사용. 조건을 만족할때까지 반복
int i = 0;
while (i < 5)
{
if (i == 4) continue;
cout << i
i++
}
// do-while문. 최소 1번이상 실행해야하는경우 사용. 1번 실행후 조건을 만족할때까지 반복
int j = 0;
do
{
cout << j;
j++;
} while (j < 5);
// for문. 정해진 횟수가 있을경우 사용. 정해진 횟수만큼 반복
for (int k = 0; k < 5; k++)
{
if (k == 4) break;
cout << k;
}
}
배열
#include <iostream>
using namespace std;
int main() {
// 문자열 배열. 변수명 뒤에 배열 크기 지정.
string companies[4] = {"Apple", "Tesla", "Google", "Nvidia"};
// 배열 크기 미지정
string cars[] = {"Hyundai", "Kia", "BMW"};
// for 문으로 순회. 배열의 크기만큼 반복
for (int i = 0; i < sizeof(companies) / sizeOf(string); i++)
{
cout << companies[i] << "\n";
}
// foreach 문으로 순회. 배열의 모든 원소를 순회
for (string car : cars) {
cout << car << "\n";
}
}