「AdventCalenderにあやかって1日1言語触ってみよう」という地獄の24日間企画。
実行環境を整えるところから、できるところまで。
開発環境はVirtualBox上にUbuntuを立てた。バージョンは以下。
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04 LTS"
初日の今日はC言語。
はじめて使ったプログラム言語なので、かなり懐かしい。
C言語について
C言語は、AT&T ベル研究所のケン・トンプソンが開発したB言語の改良として誕生した
ということで名前が「B」の次のアルファベットの「C」。
ちなみに、A言語もちゃんとあってAPLと呼ばれている。
これは「プログラミング言語」(a programming language) の略で、Aは冠詞のA。
なんともまぎらわしい…。
A言語とB言語に継承関係はなく、B言語は継承元のBCPLを略した名前。
環境構築
コンパイラの確認
gccがインストールされているか確認。
$ gcc -v
gcc version 5.3.1 20160413
実行環境整える必要なく、元からインストール済み。
Hello world
helloworld.c
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
helloworld.cをコンパイル。
$ gcc helloworld.c
出力ファイル名を -o
で名前を指定していないので、 a.out となった。
Assembler Output の略。
$ ./a.out
Hello World!
ツリー描画プログラム
24個のアスタリスクでツリーを描画する宿題的プログラミング。
学校の宿題で三角形とか書いてた。
tree.c
#include <stdio.h>
int main(void) {
const char ASTER[] = "* ";
const char SPACE[] = " ";
const int EVE = 24;
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--) printf(SPACE);
for (j = 1; j <= i; j++) printf(ASTER);
} else {
// 幹
for (j = i - trnk; j >= 1; j--) printf(SPACE);
for (j = 1; j <= trnk; j++) printf(ASTER);
}
printf("/n");
}
return 0;
}
実行
$ gcc tree.c -o tree.out
$ ./tree.out
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * *
クリスマスツリー完成。
おわり
初日から時間ギリギリの投稿…。
久々にC言語触って、「あったあった stdio.h
!」という妙なテンションなった。
明日はたぶんC++