2009-07-04から1日間の記事一覧

ヒストグラム

C K&R

K&R本 演習1-13 入力した単語の長さをヒストグラムにしてプリントするプログラムを書け。 動的にデータの長さが変わると難しいのでとりあえず固定値でやってみた #include <stdio.h> #include <math.h> #include "mylib.h" int main(void) { int num[] = { 1,2,3,2, 1,2,3,4, </math.h></stdio.h>…

キュー

http://www.geocities.jp/ky_webid/algorithm/009.htmlスタックとは違い、データの追加は後ろですが、データの取り出しは先頭からになります。 #include <stdio.h> typedef struct { int data[100]; int end; int start; } queue; void enqueue (queue *q,int data) {</stdio.h>…

スタック

http://www.geocities.jp/ky_webid/algorithm/008.htmlデータの扱い方の話ですかね。簡単に言うと配列の後ろに追加、また後ろから削除、という感じでしょうか。とりあえず適当に実装してみます。 #include <stdio.h> typedef struct { int data[100]; int index; } st</stdio.h>…

勉強用にmylib.hを作る

C

ここまでずっとC言語の勉強をしてきたわけですが、値の交換処理や配列の出力をするのにいちいちコピペでやってきました。そろそろ勉強用に良く使う関数をどこか一箇所にまとめておきたいなと思い、mylib.hなるものを作って今後はそこに何度も使う小さなプロ…

二分探索法(バイナリサーチ)

http://www.geocities.jp/ky_webid/algorithm/007.html 二分探索法は、あらかじめ配列を昇順あるいは降順にソートしておくことが前提になります。そして、まず配列の中央にある要素を調べます。もし目的の値と異なっていれば、目的の値とその位置にある値と…

入力文字を単語に切り分ける

C K&R

K&R本 演習1-12 入力した単語を1行に一つずつ印字するプログラムを書け。 表示させるだけなら単純。 #include <stdio.h> int main(void) { int c; int line = 0; while ( (c = getchar()) != EOF ) { if ( c == ' ' ) { line = 1; } else { if ( line ) { line = 0; p</stdio.h>…

単語のカウント

C K&R

K&R本 1.5.4 サンプルもあるが、自分で実装してみる。 #include <stdio.h> #include <ctype.h> // K&R 1.5.4 int main (void) { int c; int count = 0; int word = 0; FILE *fp; if ( (fp = fopen("test.txt","r")) == NULL ) { puts("file open error"); return 1; } while ( </ctype.h></stdio.h>…

空白、タブ、改行を数える

C K&R

K&R本 演習1-8 空白、タブ、改行を数えるプログラムを書け #include <stdio.h> int main (void) { int c; int count = 0; FILE *fp; if ( (fp = fopen("test.txt","r")) == NULL ) { puts("file open error"); return 1; } while( (c = fgetc(fp)) != EOF ) { switch(</stdio.h>…

getchar()

C K&R

K&R 1.5.1 #include <stdio.h> int main (void) { int c; c = getchar(); while ( c != EOF ) { putchar(c); c = getchar(); } return 0; } キーボードからの入力をそのまま出力このようなwhile文はもっとコンパクトに書けるイディオムがある。 #include <stdio.h> int main (v</stdio.h></stdio.h>…