C++/공부 정리

클래스, 재귀함수

sondiaa 2021. 10. 1. 20:26

클래스는 재사용성이 뛰어나다. 항상 그것을 염두해둬야 한다.

 

간단한 클래스 작성하기

#include <iostream>
using namespace std;
class zergling{
public:
    int hp;
    
    void run()
    {
        cout << "gogo";
    }
    void move(){
        cout << "go";
    }
};
int main()
{
    zergling t;
    t.hp = 100;
    t.run();
    t.move();
    return 0;
}

 

11

12

13

형식으로 출력하기

#include <iostream>
using namespace std;

int main()
{
    
    for(int i=1; i<4; i++)
    {
        for(int j=1; j<4; j++)
            cout << i << j << '\n';
    }
}

111

112

113 

형식으로 출력하기

#include <iostream>
using namespace std;

int main()
{
    
    for(int i=1; i<4; i++)
    {
        for(int j=1; j<4; j++)
        {
            for(int k=0; k<4; k++)
            cout << i << j <<  k << '\n';
        }
    }
}

재귀로  for문 여러번 한 것처럼 짜기

if n == 7

1111111

1111112

1111113

#include <iostream>
using namespace std;
int n, path[10];
void run(int level)
{
    if(level == n)
    {
        for(int i=0; i<level; i++)
        {
            cout << path[i];
        }
        cout << '\n';
        return;
    }
    
    for(int i=0; i<3; i++)
    {
        path[level] = i+1;
        run(level+1);
        path[level] = 0;
    }
}
int main()
{
    
    cin >> n;
    run(0);
    return 0;
}

재귀의 경우 직접 트레이스 하면서 어떻게 진행되는지 하나씩 체크하면서 보는게 좋다.

 

전역변수 사용하지 않고 0 1 2 3 2 1 0 출력해보기

#include <iostream>
using namespace std;

void run(int level)
{
    if(level == 3)
    {
        cout << 3 << ' ';
        return;
    }
    
    cout << level << ' ';
    run(level+1);
    cout << level << ' ';
}
int main()
{
    run(0);
    return 0;
}

전역변수 사용하지 않고 5 4 3 2 3 4 5 출력해보기

#include <iostream>
using namespace std;

void run(int level)
{
    if(level == 2)
    {
        cout << level << ' ';
        return;
    }
    cout << level << ' ';
    run(level - 1);
    cout << level << ' ';
}
int main()
{
    run(5);
    return 0;
}
#include <iostream>
using namespace std;

void run(int level)
{
    cout << level << ' ';
    if(level == 2)
    {
        return;
    }

    run(level - 1);
    cout << level << ' ';
}
int main()
{
    run(5);
    return 0;
}

숫자를 입력 받고 숫자 + 3 까지만 출력하기 

ex) x = 3 - > 3 4 5 6 5 4 3

#include <iostream>
using namespace std;

int x;
void run(int level)
{
    cout << level << ' ';
    if(level == x+3)
    {
        return;
    }
    
    run(level + 1);
    cout << level << ' ';
}
int main()
{
    cin >> x;
    run(x);
    return 0;
}