0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[1day1lang AdventCalender] day2 C++

Posted at

2日目はC繋がりで、今まで触ったことのないC++

1日目の記事はこちら
[1day1lang AdventCalender] day1 C言語

環境構築

コンパイラの確認

g++がインストールされているか確認

$ g++ -v
gcc version 5.4.0 20160609

昨日と同じく、元からインストール済み

Hello World!

helloworld.cpp
# include <iostream>
using namespace std;

int main() {
    cout << "Hello World!" << endl;
    return 0;
}

改行は\nでもいいが、endlがスタンダードらしい
helloworld.cppをコンパイル

$ gcc helloworld.cpp

今回も出力ファイル名を -o で名前を指定していないので、 a.out となった

$ ./a.out 
Hello World!

ツリー描画

Cのソースをそのまま移植 + 出力を printf() から cout に変えただけのもの

tree.cpp
# include <iostream>
using namespace std;

int main() {
    const char ASTER[] = "* ";
    const char SPACE[] = " ";
    const int  EVE   = 30;

    int sumAster = 0;
    int step = 0;
    int i,j;
    int trnk;

    while(sumAster <= EVE) {
        step ++;
        sumAster += step;
    }
    trnk = EVE - (sumAster - step);

    for (i = 1; i <= step; i++){
        if (i < step) {
            for (j = step; j > i; j--) cout << SPACE;
            for (j = 1; j <= i; j++)   cout << ASTER;
        } else {
            for (j = i - trnk; j >= 1; j--) cout << SPACE;
            for (j = 1; j <= trnk; j++)     cout << ASTER;
        }
	    cout << endl;
    }

    return 0;
}

実行

$ g++ tree.cpp -o tree.out
$ ./tree.out 
      * 
     * * 
    * * * 
   * * * * 
  * * * * * 
 * * * * * * 
    * * * 

おわり

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?