본문 바로가기
Language/C++

[C++_제 5장] 반복문

by 전전긍긍 2021. 10. 9.

본 포스팅은 C++로 시작하는 객체지향 프로그래밍 책을 바탕으로 작성하였습니다.

 

C++로 시작하는 객체지향 프로그래밍

『C++로 시작하는 객체지향 프로그래밍』은 구문보다는 문제 해결에 중점을 두는 문제 구동 방식을 사용한 프로그래밍에 대해 가르치고 있다. 여러 가지 상황에서 문제를 야기한 개념을 사용함

book.naver.com


key point

  • while 문은 조건이 참인 동안 반복적으로 문장을 실행한다.
  • do while 문은 우선 반복 내용이 실행되고 나서 반복 조건을 검사하는 것을 제외하고 while 문과 동일
  • for 문은 반복문을 작성하기 위한 간결한 구문이다.
  • breakcontinue 키워드는 반복문에서 부가적인 제어를 제공해 준다.

list

(접은글에서 확인)

더보기

5.1 올바른 답이 구해질 때까지 사용자가 답을 입력하는 프로그램

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
	srand(time(0));
	int num1 = rand() % 10;
	int num2 = rand() % 10;

	if (num1 < num2)
	{
		int temp = num1;
		num1 = num2;
		num2 = temp;
	}

	cout << "What is " << num1 << " - " << num2 << " ? ";
	int answer;
	cin >> answer;

	while (num1 - num2 != answer)
	{
		cout << "Wrong answer. Try again. What is" << num1 << " - " << num2 << " ? ";
		cin >> answer;
	}
	cout << "You got it!" << endl;
	return 0;
}
/*
What is 4 - 1 ? 5
Wrong answer. Try again. What is4 - 1 ? 6
Wrong answer. Try again. What is4 - 1 ? 5
Wrong answer. Try again. What is4 - 1 ? 8
Wrong answer. Try again. What is4 - 1 ? 3
You got it!
*/

 

5.2.1 예제 : 숫자 맞추기

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
	srand(time(0));
	int num = rand() % 101;

	cout << "Guess a magic between 0 and 100" << endl;
	int guess = -1;

	while (num != guess)
	{
		cout << "Enter you guess : ";
		cin >> guess;

		if (guess > num)
			cout << "Your guess is too high" << endl;
		else if (guess == num)
			cout << "Yes, the number is " << num << endl;
		else
			cout << "Yout guess is too low" << endl;
	}
	return 0;
}
/*
Guess a magic between 0 and 100
Enter you guess : 50
Your guess is too high
Enter you guess : 40
Your guess is too high
Enter you guess : 30
Your guess is too high
Enter you guess : 20
Yout guess is too low
Enter you guess : 25
Yout guess is too low
Enter you guess : 29
Yes, the number is 29
*/

 

5.2.3 예제 : 복수의 뺄셈 퀴즈

#include <iostream>
#include <ctime> //time 함수로 인해 삽입
#include <cstdlib> //rand 와 srand 함수로 인해 삽임
using namespace std;

int main()
{
	int correctCount = 0; //맞은 개수
	int count = 0; //질문개수
	//현재시간을 알아내기 위해서 time(0)함수 사용
	long startTime = time(0); // 시작 시간 설정
	const int NUMBERS_OF_QUESTION = 5; //상수선언은 관습적으로 대문자로 한다

	srand(time(0));

	while (count < NUMBERS_OF_QUESTION)
	{
		int num1 = rand() % 10; //난수 생성
		int num2 = rand() % 10;

		if (num1 < num2) //num1<num2 를 전제로 함
		{
			int temp = num1;
			num1 = num2;
			num2 = temp;
		}

		cout << "What is " << num1 << " - " << num2 << "? "; //질문
		int answer;
		cin >> answer;

		if (answer == num1 - num2)
		{
			cout << "You are correct!\n" << endl;
			correctCount++;
		}
		else
			cout << "Your answer is wrong, \n" << num1 << " - " << num2 << " should be "
			<< (num1 - num2)<< "\n" << endl;

		count++; //1개의 질문이 끝나면 후위증가로 coune 개수 늘려주기
	}

	long endTime = time(0); //끝나는 시간 설정
	long testTime = endTime - startTime;

	cout << "Correct count is " << correctCount << "\nTest time is " << testTime << " seconds\n";

	return 0;
}

/*
What is 6 - 6? 0
You are correct!

What is 5 - 1? 5
Your answer is wrong,
5 - 1 should be 4

What is 2 - 2? 5
Your answer is wrong,
2 - 2 should be 0

What is 7 - 3? 4
You are correct!

What is 8 - 7? 1
You are correct!

Correct count is 3
Test time is 15 seconds
*/

 

5.2.4 복수의 뺄셈 퀴즈를 사용자 확인으로 반복문 제어

#include <iostream>
#include <ctime> //time 함수로 인해 삽입
#include <cstdlib> //rand 와 srand 함수로 인해 삽임
using namespace std;

int main()
{
	int correctCount = 0; //맞은 개수
	char continueLoop = 'Y'; //질문의 개수를 제한하지 않고 사용자가 제한하도록
	//현재시간을 알아내기 위해서 time(0)함수 사용
	long startTime = time(0); // 시작 시간 설정

	srand(time(0));

	while (continueLoop == 'Y')
	{
		int num1 = rand() % 10; //난수 생성
		int num2 = rand() % 10;

		if (num1 < num2) //num1<num2 를 전제로 함
		{
			int temp = num1;
			num1 = num2;
			num2 = temp;
		}

		cout << endl << "What is " << num1 << " - " << num2 << "? "; //질문
		int answer;
		cin >> answer;

		if (answer == num1 - num2)
		{
			cout << "You are correct!\n" << endl;
			correctCount++;
		}
		else
			cout << "Your answer is wrong, \n" << num1 << " - " << num2 << " should be "
			<< (num1 - num2)<< "\n" << endl;

		cout << "Enter Y to continue and N to quit: "; //계속할건지 나갈건지
		cin >> continueLoop;
	}

	long endTime = time(0); //끝나는 시간 설정
	long testTime = endTime - startTime;

	cout << "Correct count is " << correctCount << "\nTest time is " << testTime << " seconds\n";

	return 0;
}
/*

What is 9 - 7? 2
You are correct!

Enter Y to continue and N to quit: Y

What is 9 - 2? 4
Your answer is wrong,
9 - 2 should be 7

Enter Y to continue and N to quit: Y

What is 8 - 7? 1
You are correct!

Enter Y to continue and N to quit: N
Correct count is 2
Test time is 12 seconds
*/

 

5.5 감시 값을 이용한 루프제어 (지정되지 않은 개수의 정수를 읽고 합을 계산하는 프로그램)

위에 예제랑 다른 방식

반복문을 제어하는 방법은 여러가지, 그 중에 하나가 감시값을 이용한 루프제어

입력의 끝을 나타내기 위해서 감시 값을 사용 (이 예제에서는 감시 값이 0)

#include <iostream>
using namespace std;

int main()
{
	cout << "Enter an interger (the input ends" <<
		" if is is 0): ";
	int data;
	cin >> data;

	int sum = 0;
	while (data != 0)
	{
		sum += data;
		cout << "\nEnter an integer (the input ends " <<
			" if it is 0) : ";
		cin >> data;
	}

	cout << "\nThe sum is " << sum << endl;

	return 0;
}
/*
Enter an interger (the input ends if is is 0): 5

Enter an integer (the input ends  if it is 0) : 4

Enter an integer (the input ends  if it is 0) : 1

Enter an integer (the input ends  if it is 0) : 8

Enter an integer (the input ends  if it is 0) : 0

The sum is 18
*/

 

5.8.1 예제 : 최대공약수 구하기

#include <iostream>
using namespace std;

int main()
{
	int gcd = 1;
	int n1, n2;
	cout << "n1, n2값을 입력해주세요: ";
	cin >> n1 >> n2;

	for (int k = 2; k <= n1 && k <= n2; k++)
	{
		if (n1 % k == 0 && n2 % k == 0)
			gcd = k;
	}
	cout << "최대공약수는 " << gcd;
	return 0;
}
//n1, n2값을 입력해주세요: 125 2525
//최대공약수는 25

 

5.8.2 예제 : 미래의 등록금 예측

#include <iostream>
using namespace std;

int main()
{
	double k = 10000;
	int year;
	for (year = 0; k < 20000; year++)
	{
		k = k * 0.07 + k;
		cout << k << endl;
	}
	cout << "등록금이 약 두배가 되려면 " << year << "년 을 기다려야 하고 최종 등록금은 " << k;
	return 0;
}
/*
10700
11449
12250.4
13108
14025.5
15007.3
16057.8
17181.9
18384.6
19671.5
21048.5
등록금이 약 두배가 되려면 11년 을 기다려야 하고 최종 등록금은 21048.5
*/

 

5.8.4 예제 : 몬테카를로 시뮬레이션

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
	//상수선언
	const int NUMBER_OF_TRIALS = 1000000;
	//원 안에 있는 점 count
	int numberOfHits = 0;
	//랜덤
	srand(time(0));

	for (int i = 0; i < NUMBER_OF_TRIALS; i++)
	{
		double x = rand() * 2.0 / RAND_MAX - 1;
		double y = rand() * 2.0 / RAND_MAX - 1;
		if (x * x + y * y <= 1)
			numberOfHits++;
	}

	double PI = 4.0 * numberOfHits / NUMBER_OF_TRIALS;
	cout << "PI is " << PI << endl;
	return 0;
}

//PI is 3.13913

 

5.8.4 예제 : 10진수를 16진수로 변환

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	cout << "10진수를 입력해주세요 : ";
	int decimal;
	cin >> decimal;
	string hex = "";

	while (decimal!= 0)
	{
		int hexValue = decimal % 16;

		char hexChar = (hexValue <= 9 && hexValue>= 0) ?
			static_cast<char>(hexValue + '0') :
			static_cast<char>(hexValue - 10 + 'A');

		hex = hexChar + hex;
		decimal = decimal / 16;
	}
	cout << "The hax number is " << hex << endl;
	return 0;
}
//10진수를 입력해주세요 : 58
//The hax number is 3A

 

5.16 예제 : 회문검사

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string s;
	cout << "문자를 입력해주세요 (회문 판단) : ";
	getline(cin, s);

	int low = 0;
	int high = s.length ()- 1;

	bool palindrome = true;

	while (low < high)
	{
		if (s[low] != s[high])
		{
			palindrome = false;
			break;
		}
		low++;
		high--;
	}
	if (palindrome)
		cout << s << "는 회문입니다." << endl;
	else
		cout << s << "는 회문이 아닙니다." << endl;

	return 0;
}
//문자를 입력해주세요 (회문 판단) : abcba
//abcba는 회문입니다.

프로그래밍 실습

 

5.1 양수와 음수의 수를 계산하고 평균 구하기

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int count = 0;
	int num = 1;
	double sum = 0.0;
	int nega = 0;
	int posi = 0;

	while (num != 0)
	{
		cout << "임의의 정수를 입력하세요: ";
		cin >> num;
		if (num == 0) {
			cout << "No numbers are entered except 0" << endl;
			break;
		}
		else if (num < 0)
			nega++;
		else if (num > 0)
			posi++;

		count++;
		sum += num;
	}


	double mean = sum / count;
	cout << "합계 : " << sum << " 평균 : " << fixed << setprecision(2) << mean << endl;
	cout << "총 개수 : " << count << endl;
	cout << "양수의 개수 : " << posi << endl;
	cout << "음수의 개수 : " << nega << endl;
	return 0;
}
/*
임의의 정수를 입력하세요: 1
임의의 정수를 입력하세요: 2
임의의 정수를 입력하세요: -1
임의의 정수를 입력하세요: 3
임의의 정수를 입력하세요: 0
No numbers are entered except 0
합계 : 5 평균 : 1.25
총 개수 : 4
양수의 개수 : 3
음수의 개수 : 1
*/

 

5.3.1 킬로그램을 파운드로 변환

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int i = 1;
	double j;

	while (i < 200)
	{
		if (i % 2 != 0)
		{
			j = i * 2.2;
			cout << left;
			cout << setw(9) << i << "\t" << setw(6) << j << endl;
		}
		i++;
	}
}
/*
1               2.2
3               6.6
5               11
7               15.4
...

193             424.6
195             429
197             433.4
199             437.8

*/

5.3.2 (for문)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	cout << "kilograms \tPounds" << endl;
	for (int i = 1; i < 200; i++)
	{
		if (i % 2 != 0)
		{
			double j = i * 2.2;
			cout << left;
			cout << setw(9) << i << "\t" << setw(6) << j << endl;
		}
	}
	return 0;
}

 

5.10 최고득점 찾기 (for문)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int stunum;
	cout << "학생 수를 입력해주세요: ";
	cin >> stunum;

	string name;
	double grade = -1;
	
	for (int i=0; i < stunum; i++)
	{
		cout << "학생 이름 입력: ";
		string name1;
		cin >> name1;

		cout << "학생 점수 입력: ";
		double score1;
		cin >> score1;

		if (grade < score1)
		{
			grade = score1;
			name = name1;

		}
	}
	cout << "최고 득점을 받은 학생의 이름과 점수 : " << name << "  " << grade;

	return 0;
}
/*
학생 수를 입력해주세요: 4
학생 이름 입력: 카리나
학생 점수 입력: 17
학생 이름 입력: 윈터
학생 점수 입력: 62
학생 이름 입력: 지젤
학생 점수 입력: 89
학생 이름 입력: 닝닝
학생 점수 입력: 92
최고 득점을 받은 학생의 이름과 점수 : 닝닝  92
*/

* 문자형이라서 처음에 char형을 했는데 char형은 1byte이기 때문에 string함수를 써야 한다.

* 학생이름과 점수를 따로 하는 것이 더 편하다.

 

5.11 최고득점 두 번째까지 찾기 (while 문)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	cout << "학생 수를 입력해주세요: ";
	int numstu;
	cin >> numstu;

	string name;
	string name2;
	double grade = -1;
	double grade2 = -1;
	int i = 0;

	while (i < numstu)
	{
		cout << "학생 이름을 입력해주세요 : ";
		string name1;
		cin >> name1;

		cout << "학생 점수를 입력해주세요 : ";
		double score1;
		cin >> score1;

		if (grade < score1)
		{
			grade = score1;
			name = name1;
		}
		else if (grade > score1)
		{
			if (grade2 < score1)
			{
				grade2 = score1;
				name2 = name1;
			}
		}


		i++;

	}
	cout << "최고득점 학생의 이름 및 점수 " << name << "  " << grade << endl;
	cout << "차점자 이름 및 점수 " << name2 << "  " << grade2 << endl;

	return 0;
}
/*
학생 수를 입력해주세요: 5
학생 이름을 입력해주세요 : A
학생 점수를 입력해주세요 : 98
학생 이름을 입력해주세요 : B
학생 점수를 입력해주세요 : 25
학생 이름을 입력해주세요 : C
학생 점수를 입력해주세요 : 46
학생 이름을 입력해주세요 : D
학생 점수를 입력해주세요 : 85
학생 이름을 입력해주세요 : E
학생 점수를 입력해주세요 : 36
최고득점 학생의 이름 및 점수 A  98
차점자 이름 및 점수 D  85
*/

* 다중 if문 사용

 

5.12 5와 6으로 나누어지는 수 찾기 (do - while문)

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int i = 100;
	int count = 1;

	do
	{
		if (i % 5 == 0 && i % 6 == 0)
		{
			(count++ % 10 != 0) ? cout << setw(4) << i : cout << setw(4) << i << "\n";
		}
		i++;
	} while (i <= 1000);

	return 0;
}
/*
 120 150 180 210 240 270 300 330 360 390
 420 450 480 510 540 570 600 630 660 690
 720 750 780 810 840 870 900 930 960 990
*/

* 이 문제의 핵심 포인트는 "한 줄에 10개씩 1자리 공백을 포함하여" 이다. 반복하니까 count는 1씩 커질테고, 10으로 나누어진다면 줄바꿈을 하도록 설정을 한 것이다.

'Language > C++' 카테고리의 다른 글

[C++_제 6장] 함수  (0) 2021.11.23
[C++_백준] if문 ( 1330, 9498, 2753, 14681, 2884 )  (0) 2021.11.08
[C++_제 4장] 수학 함수, 문자, 문자열  (0) 2021.10.09
[C++_제 3장] 선택문  (0) 2021.10.03
[C++_제 2장] 기본 프로그래밍  (0) 2021.10.03