C++

C++| 반복문과 업앤다운 게임 로직

|연두| 2025. 7. 14. 17:35

for문


선생님께서 if문만 있으면 모든 게임을 만들 수 있다고 하셨다
그런데 for문까지 있다면...?


#include <iostream>

using namespace std;

void main()
{
	//반복문
	//뭔가 반복하는 앤가? (true)
	//조건이 true일때 동작한다

	int i;

	//1. for문
	for (int i = 0; i < 10; i++)
	{
		//cout << "비야 그치렴" << endl;
		//cout << i << endl;
	}

	for ( i = 10; i >= 0; i--)
	{
		cout << i << endl;
	}

	for ( i = 1; i < 10000; i *= 2)
	{
		cout << i << endl;
	}



	/*
	a++ 후치
	++a 전치

	int a = 3;
	a 변수의 값이 b에 넘어간 이후에 연산을 한다 (후치)
	int b = a++;
	연산한 후에 a의 변수 값이 b에 대입된다 (전치)
	b = ++a;

	cout << b << endl;

	당연히 --는 -1과 같다
	b--;
	--b;
	*/
	
    /*관습적으로 2중 for문까지는 쓰지만 3중 for문은 쓰지 않는다*/
    
    	for (int i = 1; i < 10; i++)
	{
		for (int j = 1; j < 10; j++)
		{
			cout << i << "x" << j << "=" << i * j << endl;
		}
	}


}

 


 

 

while문


	//2. while문
	//기본적으로 무한 반복
	//당연히 true일 때만
	
	while (true)
	{
		cout << "살려줘" << endl;
	}​




제어문
//제어문
//break : 연산을 중지하고 빠져나간다
//continue : 연산을 건너뛴다
//return : 값을 반환하고 종료한다
//go to : 업계에선 약간 금기어..볼드모트


void main()
{
	for (int i = 0; i < 10; i++)
	{
		if (i == 3) continue;
		cout << i << endl;
	}

}​

 

업앤다운 게임 로직

직접 게임 로직을 짜보려고 하니, 간단한 게임도 생각보다 쉽지는 않았다.
역시 코드는 많이 쳐보는 게 좋은 것 같다. 

 

#include<iostream>
#include<time.h>

using namespace std;

void main()

{
	srand(time(NULL));

		int cnumber = rand() % 100 + 1;
		int pnumber;
		int count = 9;

		while (true)
		{
			cout << "맞춰봐! 1~100까지 아무 숫자나 말하기." << endl;
			cin >> pnumber;


			if (cnumber == pnumber)
			{
				cout << "정답!" << endl;
				break;
			}
			else if (cnumber > pnumber) cout << "업" << endl;
			else if (cnumber < pnumber) cout << "다운" << endl;

			cout << count << "회 남았습니다" << endl;
			count--;

			if (count < 0)
			{
				cout << "패배입니다. 다음에 다시 시도하세요." << endl;
				break;
			}
			if (count < 4)
			{
				cout << "신중하세요" <<count<<"번 남았음" << endl;
			}
		}


}