Programing/C++

C++로 별 찍기 (for문)

hye3193 2023. 10. 25. 12:52

과제 할 겸 시험 공부할 겸 짜두었던 C++ 별 찍기 코드

i, j 변수는 for문 안에서 선언해주는 게 더 낫겠지만 int 붙이기 귀찮아서 그냥 맨 위쪽에 선언해버렸다...

 

1.

 *
 **
 ***
 ****
 *****
 ******
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for(i = 1; i < 7; i++)
    {
        for(j = 0; j < i; j++){
            cout << "*";
        }
        cout << endl;
    }
}

 

2.

      *
     **
    ***
   ****
  *****
 ******
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for(i = 1; i < 7; i++)
    {
        for(j = 0; j < i; j++){
            cout << "*";
        }
        cout << endl;
    }
}

 

3.

      *
     ***
    *****
   *******
  *********
 ***********
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for (i = 1; i < 7; i++)
    {
        for (j = 0; j < 6 - i; j++)
        {
            cout << " ";
        }
        for (j = 0; j < 2 * i - 1; j++)
        {
            cout << "*";
        }
        cout << endl;
    }
}

 

4.

******
*****
****
***
**
*
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for(i = 6; i > 0; i--)
    {
        for(j = 0; j < i; j++){
            cout << "*";
        }
        cout << endl;
    }
}

 

5.

******
 *****
  ****
   ***
    **
     *
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for (i = 6; i > 0; i--)
    {
        for (j = 6; j > i; j--)
        {
            cout << " ";
        }
        for (j = 0; j < i; j++){
            cout << "*";
        }
        cout << endl;
    }
}

 

6.

***********
 *********
  *******
   *****
    ***
     *
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for (i = 6; i > 0; i--)
    {
        for (j = 0; j < 6 - i; j++)
        {
            cout << " ";
        }
        for (j = 0; j < 2 * i - 1; j++)
        {
            cout << "*";
        }
        cout << endl;
    }
}

 

7.

      *
     ***
    *****
   *******
  *********
 ***********
  *********
   *******
    *****
     ***
      *
#include <iostream>

using namespace std;

int main(){
    int i, j;
    
    for (i = 5; i > -6; i--){
        for (j = 0; j < abs(i); j++){
            cout << " ";
        }
        for (j = 0; j < 11 - 2 * abs(i); j++){
            cout << "*";
        }
        cout << endl;
    }
}

마름모 같이 생긴 모양의 경우 절댓값 함수 abs()를 사용해주면 for문 세 개로 표현이 가능하다