CH.05 흐름제어
5.1 제어 흐름 개요(Control flow)
5.2 조건문 if
#include <iostream>
using namespace std;
int min(int x, int y)
{
if (x > y)
return y;
else
return x;
/* if (x > y) return y;
else return x; */
// return (x > y) ? y : x;
}
int main()
{
int x;
cin >> x;
if (x > 10)
{
cout << x << " is greater than 10" << endl;
cout << "Test 1" << endl;
}
else
cout << x << " not is greater than 10" << endl;
// if else문 에서 선언된 변수들은 if else문 안에서만 유효함.
if (1)
{
int x = 5;
}
else
int x = 6;
cout << x << endl;
if (x > 10)
cout << "x is greater than 10" << endl;
else if (x < 10)
cout << "x not is greater than 10" << endl;
else // if (x == 10)
cout << "x is exactly 10" << endl;
// else는 가장 가까이 있는 if에 붙는다. 하지만 {}을 안치면 봤을때 헷갈릴 수 있으니 명확하게 {}쳐주는 것이 좋다.
if (x >= 10)
{
if (x <= 20)
cout << "x is between 10 and 20" << endl;
}
else
cout << "..." << endl;
if (x >= 10)
{
if (x <= 20)
cout << "x is between 10 and 20" << endl;
else
cout << "..." << endl;
}
int x1, y1;
cin >> x1 >> y1;
if (x1 == y1)
cout << "same numbers" << endl;
else
cout << "Not same" << endl;
if (x1 > 0 && y1 > 0)
cout << "both numbers are positive" << endl;
else if (x1 > 0 || y1 > 0)
cout << "one of the numbers is positive" << endl;
else
cout << "Neither number is positive" << endl;
int x2;
cin >> x2;
if (x2 > 10)
cout << "A" << endl;
else if (x2 == -1)
return 0;
else if (x2 < 0)
cout << "B" << endl;
//1, 2는 같다. null statement.
if (x > 10) // 1.
;
if (x > 10) // 2.
{
};
if (x = 1) // x = 1; if(x) 이런 의미.
cout << x << endl;
return 0;
}
5.3 switch-case
#include <iostream>
using namespace std;
enum class Colors
{
BLACK,
WHITE,
RED,
GREEN,
BLUE
};
void printColorName(Colors color)
{
/*if (color == Colors::BLACK)
cout << "Black" << endl;
else if (color == Colors::WHITE)
cout << "White" << endl;
else if ........ 아 귀찮아.. 이때 사용하는게 switch-case임. */
/*switch (color)
{
case Colors::BLACK :
cout << "Black";
case Colors::BLUE :
cout << "BLUE";
......... 아 귀찮아... color를 cast 해보자
}*/
switch (static_cast<int>(color))
{
case 0:
cout << "Black" << endl;
break;
case 1:
cout << "White" << endl;
break;
case 2:
cout << "Red" << endl;
break;
case 4:
cout << "Green" << endl;
break;
case 5:
cout << "Blue" << endl;
break;
}
}
int main()
{
//printColorName(Colors::BLACK);
int x;
cin >> x;
// 의도적으로 break;를 안넣을 수도 있다.
{
switch (x)
{
case 0:
cout << "Zero";
break;
case 1:
cout << "One";
break;
case 2:
cout << "Two";
break;
}
cout << endl;
}
int x1;
cin >> x1;
switch (x1)
{
int a;
// int b = 5; 변수 선언은 할 수 있지만 초기화는 안된다. 값을 대입하는 건 case문 안에서 해야됨.
// case문 안에서도 변수 선언 할 수 있다.
case 0:
a = 1;
cout << a << endl;
break;
// case문 안에서 변수 선언을 했을때 밖에서 int a; 밖에서 선언 한것과 같은 기능을 수행하기 때문에
// 다른 case문 안에서 사용 할 수 있다.
// 하지만 대입값은 각각의 case문 안에서만 사용이 가능하다.
case 1:
int y;
y = 5;
break;
case 2:
y = 5; // y값 대입을 안해줬을 경우 case 1 안에 있는 y = 5가 실행이 안되기에 garbage값이 들어간다.
cout << y << endl;
// default는 case가 없는 모든 경우에 실행됨.
default:
cout << "Undefined input" << x1 << endl;
}
return 0;
}
5.4 goto
#include <iostream>
#include <cmath> // sqrt()
using namespace std;
int main()
{
double x;
tryAgain : //label
cout << "Enter a non-negative number" << endl;
cin >> x;
if (x < 0.0)
goto tryAgain;
cout << sqrt(x) << endl;
return 0;
}
5.5 반복문 while
#include <iostream>
using namespace std;
int main()
{
int count1 = 0;
while (1)
{
cout << count1 << endl;
++count1;
if (count1 == 10) break;
}
////overflow
//unsigned int count2 = 10;
//while (count2 >= 0)
//{
// if (count2 == 0) cout << "zero";
// else cout << count2 << " ";
// count2--;
//}
int count = 1;
while (count < 100)
{
if (count % 5 == 0) cout << "Hello " << count << endl;
count++;
}
int outer_count = 1;
while (outer_count <= 5)
{
int inner_count = 1;
while (inner_count <= outer_count)
{
cout << inner_count++ << " ";
}
cout << endl;
++outer_count;
}
return 0;
}
practice
- 마지막 반복문의 결과를 거꾸로 출력되게 만들어 보라. (1,2,3,4,5/ 1,2,3,4/ 1,2,3/ 1,2/ 1)
5.6 반복문 do_while
#include <iostream>
using namespace std;
int main()
{
int selection;
do
{
cout << "1. add" << endl;
cout << "2. sub" << endl;
cout << "3. mult" << endl;
cout << "4. div" << endl;
cin >> selection;
} while (selection <= 0 || selection >= 5);
cout << "You selected " << selection << endl;
return 0;
}
5.7 반복문 for
#include <iostream>
using namespace std;
int pow(int base, int exponent)
{
int result = 1;
for (int count = 0; count < exponent; count++)
result *= base;
return result;
}
int main()
{
for (int count2 = 0; count2 < 10; ++count2)
{
cout << count2 << endl;
}
// cout << count << endl; 실행 안됨.
int count = 0;
for (; count < 10; ++count)
{
cout << count << endl;
}
cout << count << endl; // 실행 가능.
// while(true)와 같은 무한 루프 가운데에 true 써도 됨.
/*for (;; ++count)
{
cout << count << endl;
}*/
for (int i = 0, j = 0; (i + j) < 10; ++i, j += 2)
{
cout << i << " " << j << endl;
}
for(int j = 0; j < 9; ++j)
for (int i = 0; i < 9; ++i)
{
cout << i << " " << j << endl;
}
/* for (unsigned int i = 9; i >= 0; --i)
cout << i << endl; */
return 0;
}
5.8 break, continue
#include <iostream>
using namespace std;
void breakOrReturn()
{
while (true)
{
char ch;
cin >> ch;
if (ch == 'b')
break; // while이 끝나니 Hello 출력
if (ch == 'r')
return; // 함수가 끝나니 Hello 출력 X
}
cout << "Hello" << endl;
}
int main()
{
//int count = 0;
//while (true)
//{
// cout << count << endl;
// if (count == 10) break;
// count++;
//}
// breakOrReturn();
for (int i = 0; i < 10; ++i)
{
if (i % 2 == 0) continue;
cout << i << endl;
}
int count1(0);
do
{
if (count1 == 5)
continue;
cout << count1 << endl;
count1++;
} while (++count1 < 10); // while(count < 10)하면 무한루프 걸림.
// int count(0);
// bool escape_flag = false;
// while (!escape_flag)
// {
// char ch;
// cin >> ch;
// cout << ch << " " << count++ << endl;
// if (ch == 'x')
// escape_flag = true;
// }
int count(0);
while (1)
{
char ch;
cin >> ch;
cout << ch << " " << count++ << endl;
if (ch == 'x')
break;
}
return 0;
}
5.9 난수 만들기(random numbers)
#include <iostream>
#include <cstdlib> // std::rand(), std::srand()
#include <ctime> // std::time()
#include <random>
using namespace std;
// *number twister*
//
// unsigned int PRNG() // Pseudo Random Number Generator
// {
// static unsigned int seed = 5523;
//
// seed = 8253729 * seed + 2396403;
//
// return seed % 32768;
// }
//
int getRandomNumber(int min, int max)
{
static const double fraction = 1.0 / (RAND_MAX + 1.0);
return min + static_cast<int>((max - min + 1) * (std::rand() * fraction));
}
int main()
{
// std::srand(5323); //seed
std::srand(static_cast<unsigned int>(std::time(0))); //debug가 필요하면 seed 고정시켜야됨.
for (int count = 1; count <= 100; ++count)
{
/* cout << std::rand() << "\t";*/
cout << getRandomNumber(5, 8) << "\t";
if (count % 5 == 0) cout << endl;
}
std::random_device rd;
std::mt19937_64 mersenne(rd()); // create a mesenne twister
std::uniform_int_distribution<> dice(1, 6);
for (int count = 1; count <= 20; ++count)
cout << dice(mersenne) << endl;
return 0;
}
5.10 std::cin 더 잘 쓰기( ignore(), clear(), fail() )
#include <iostream>
using namespace std;
int getInt()
{
while (true)
{
cout << "Enter an integer number : ";
int x;
cin >> x;
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(32767, '\n');
cout << "Invaild number, please try again" << endl;
}
else
{
std::cin.ignore(32767, '\n');
return x;
}
}
}
char getOperator()
{
while (true)
{
cout << "Enter an operator (+, -) : ";
char op;
cin >> op;
std::cin.ignore(32767, '\n');
if (op == '+' || op == '-')
return op;
else
cout << "Invaild operator, please try again" << endl;
}
}
void printResult(int x, char op, int y)
{
if (op == '+') cout << x + y << endl;
else if (op == '-') cout << x - y << endl;
else {
cout << "Invalid operator" << endl;
}
}
int main()
{
int x = getInt();
char op = getOperator();
int y = getInt();
printResult(x, op, y);
return 0;
}
'Computer language' 카테고리의 다른 글
Programming: Principles and Practice Using C++ (0) | 2020.09.15 |
---|---|
[Ch.04] 홍정모의 따라하며 배우는 C++ < 변수 범위와 더 다양한 변수형> (0) | 2020.09.08 |
[Ch.03] 홍정모의 따라하며 배우는 C++ < 연산자들> (0) | 2020.09.06 |
[Ch.02] 홍정모의 따라하며 배우는 C++ (0) | 2020.09.06 |
[Ch.01] 홍정모의 따라하며 배우는 C++ (0) | 2020.09.05 |