문서의 이전 판입니다!
C++ 스터디 #2: 연산자, 조건, 반복
2021년 3월 25일 목요일 8:30
Google Meet
출처: https://dojang.io/course/view.php?id=2 (코딩도장)
1. 관계 연산자
1.1. 관계 연산자 예시
#include <iostream>
using namespace std;
int main(void)
{
int x = 1, y = 2;
cout << "== 관계 연산자: " << (x == y) << endl;
cout << "!= 관계 연산자: " << (x != y) << endl;
cout << "> 관계 연산자: " << (x > y) << endl;
cout << "< 관계 연산자: " << (x < y) << endl;
cout << ">= 관계 연산자: " << (x >= y) << endl;
cout << "<= 관계 연산자: " << (x <= y) << endl;
return 0;
}
2. 논리 연산자
2.1. 논리 연산자 예시
#include <iostream>
using namespace std;
int main(void)
{
int x = 5, y = 6, z=7;
cout << "&& 논리 연산자 True: " << ((x < y) && (y < z)) << endl;
cout << "|| 논리 연산자 True: " << ((x < y) || (y > z)) << endl;
cout << "! 논리 연산자 True: " << (!(x > y)) << endl;
cout << "&& 논리 연산자 False: " << ((x < y) && (y > z)) << endl;
cout << "|| 논리 연산자 False: " << ((x > y) || (y > z)) << endl;
cout << "! 논리 연산자 False: " << (!(x < y)) << endl;
return 0;
}
3. if문
3.1.1 if 반복문 예시(1)
#include <iostream>
using namespace std;
int main()
{
int x = 10;
if (x == 10)
{
cout << "10입니다." << endl;
}
return 0;
}
3.1.2 if 반복문 예시(2): else
#include <iostream>
using namespace std;
int main()
{
int x = 20;
if (x == 10)
{
cout << "10입니다." << endl;
}
else
{
cout << "10이 아닙니다." << endl;
}
return 0;
}
3.1.3 if 반복문 예시(3): else if
#include <iostream>
using namespace std;
int main()
{
int x = 20;
if (x == 10)
{
cout << "10입니다." << endl;
}
else if(x>10)
{
cout << "10보다 큽니다." << endl;
}
else
{
cout << "10보다 작습니다." << endl;
}
return 0;
}
3.1.4 if 반복문 예시(4): 논리 연산자
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 20;
if (x<y)
{
cout << "x는 y보다 작다." << endl;
}
else if(x>y)
{
cout << "x는 y보다 크다." << endl;
}
else
{
cout << "x와 y는 같다." << endl;
}
return 0;
}
3.1.5 if 반복문 예시(5): 관계 연산자
#include <iostream>
using namespace std;
int main()
{
int x = 10, y = 20, z=30;
if ((x < y) && (x < z))
{
cout << "x는 y와 z보다 작다." << endl;
}
if (!(x > y))
{
cout << "x가 y보다 크다" << endl;
}
return 0;
}
4. for 반복문
4.1.1 for 반복문 예시(1)
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 100; i++)
{
cout<<"Hello, world! "<<i<<endl;
}
return 0;
}
4.1.2 for 반복문 예시(2): 이중 for문
#include <iostream>
using namespace std;
int main()
{
for (int i = 5; i > 0; i--)
{
for (int j = 5; j > 0; j--)
{
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}
return 0;
}
5. while 반복문
5.1. while 반복문 예시(1)
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i < 100)
{
cout<< "Hello, world! "<<i<<endl;
i++;
}
return 0;
}
6. break
break는 for, while 문법에서 반복을 벗어나기 위해 사용합니다.
6.1. break 예시(1)
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (1)
{
i++;
cout << i << endl;
if (i == 100)
break;
}
return 0;
}
7. continue
continue는 반복을 유지한 상태에서 코드의 실행만 건너뛰는 역할을 합니다. 마치 카드 게임을 할 때 패가 안 좋으면 판을 포기하는 것과 같습니다.
7.1. continue 예시(1)
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 100; i++)
{
if (i % 2 != 0)
continue;
cout << i << endl;
}
return 0;
}





