C++ 스터디 #4: Phase 1 복습 및 심화내용

시간 2021년 5월 6일 목요일 20:30 ~ 22:10
장소 Google Meet
참가자 -

출처: https://boycoding.tistory.com/186?category=1009239 [소년코딩]

switch 표현식이 값을 평가하고, 각 case 레이블의 값과 같은지 테스트합니다. 레이블의 값과 같으면 레이블 뒤의 명령문을 실행합니다. 일치하는 레이블이 없으면 default 뒤의 명령문을 실행합니다.

#include <iostream>
using namespace std;

int main()
{
    int num;
    cin >> num;

    switch(num)
    {
    case 1:
        cout << "One";
        break;
    case 2:
        cout << "Two";
        break;
    default:
        cout << "Unknown";
        break;
    }

    return 0;
}



출력

표준 입력으로 문자 'f', 'c', 'p' 중 하나가 입력됩니다. 입력된 문자가 'f'라면 “환타”, 'c'라면 “콜라”, 'p'라면 “포카리스웨트”를 출력하고, 아무 문자에도 해당되지 않으면 “판매하지 않는 메뉴”를 출력하는 프로그램을 만드세요.


출력 예시

f
환타


코드

#include <iostream>
using namespace std;

int main()
{
	char menu;
	cin >> menu;

	switch (menu)
	{
	case 'f':
		cout << "환타";
		break;
	case 'c':
		cout << "콜라";
		break;
	case 'p':
		cout << "포카리스웨트";
		break;
	default:
		cout << "판매하지 않는 메뉴";
		break;
	}

	return 0;
}



출력 예시

*****
*****
*****
*****


코드

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 4; i++)
	{
		for (int j = 1; j <= 5; j++) 
		{
			cout << "*";
		}

		cout << endl;
	}

	return 0;
}



출력 예시

*
**
***
****
*****


코드

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 5; i++)
	{
		for (int j = 1; j <= i; j++) 
		{
			cout << "*";
		}

		cout << endl;
	}

	return 0;
}



출력 예시

*****
 ****
  ***
   **
    *


코드

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 5; i++)
	{
		for (int j = 1; j <= 5; j++) 
		{
			if (j < i)
				cout << " ";
			else
				cout << "*";
		}

		cout << endl;
	}

	return 0;
}



출력 예시

    *
   ***
  *****
 *******
*********


코드

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 5; i++)
	{
		for (int j = 1; j <= 9; j++)
		{
			if (j > 5 - i && j < 5 + i)
				cout << "*";
			else
				cout << " ";
		}

		cout << endl;
}



출력

1부터 100까지 자연수를 차례대로 출력하는데, 3의 배수면 숫자 대신 ‘Fizz’를 출력, 5의 배수면 ‘Buzz’를 출력, 둘 다 해당되면 ‘FizzBuzz’를 출력하도록 하는 프로그램을 작성하세요.


출력 예시

1
2
Fizz
4

.
.
.

98
Fizz
Buzz


코드

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i <= 100; i++)
	{
		if (i % 3 == 0 && i % 5 == 0)
			cout << "FizzBuzz" << endl;
		else if (i % 3 == 0)
			cout << "Fizz" << endl;
		else if (i % 5 == 0)
			cout << "Buzz" << endl;
		else
			cout << i << endl;
	}

	return 0;
}
아래와 같이 else&& 없이도 구현이 가능합니다.
#include <iostream>
using namespace std;

int main(){
	for (int i = 1; i <= 100; i++)	{
		bool nothing = true;

		if (i % 3 == 0){  //3의배수
			cout << "Fizz";
			nothing = false;
		}

		if (i % 5 == 0){  //5의배수
			cout << "Buzz";
			nothing = false;
		}

		if(nothing){  //3의배수도, 5의배수도 아닌
			cout << i;
		}

		cout << endl;
	}
	return 0;
}

  • activity/public/2021/cpp/210506.txt
  • 마지막으로 수정됨: 3년 전
  • 저자 david