2013年4月28日日曜日

開発環境

プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第4章(関数とプログラム構造)、4.10(再帰 (Recursion))の演習4-12、4-13を解いてみる。

その他参考書籍

演習 4-12.

コード

sample.c

#include <stdio.h>

void itoa(int n, char s[]);

int main()
{
    char s1[1000], s2[1000], s3[1000], s4[1000], s5[1000];

    itoa(0, s1);
    itoa(10, s2);
    itoa(12, s3);
    itoa(-10, s4);
    itoa(-12345, s5);

    printf("%s\n%s\n%s\n%s\n%s\n", s1, s2, s3, s4, s5);
    return 0;
}

void itoa(int n, char s[])
{
    static int i;
    if (n / 10)
        itoa(n / 10, s);
    else {
        i = 0;
        if (n < 0)
            s[i++] = '-';
    }
    s[i++] = (n < 0 ? -n : n) % 10 + '0';
    s[i] = '\0';
}

入出力結果(Terminal)

$ ./a.out
0
10
12
-10
-12345
$

演習 4-13.

コード

sample.c

#include <stdio.h>

void reverse(char s[]);
void reverse1(char s[], int i);

int main()
{
    char s1[] = "";
    char s2[] = "c";
    char s3[] = "1234567890";
    char s4[] = "kamimura";
    reverse(s1);
    reverse(s2);
    reverse(s3);
    reverse(s4);
    printf("%s\n%s\n%s\n%s\n", s1, s2, s3, s4);
    return 0;
}

void reverse(char s[])
{
    reverse1(s, 0);
}

void reverse1(char s[], int i)
{
    int len = -1, tmp_c, j;
    while(s[++len] != '\0')
        ;
    j = len - 1 - i;
    if (i < j) {
        tmp_c = s[i];
        s[i] = s[j];
        s[j] = tmp_c;
        reverse1(s, ++i);
    }
}

入出力結果(Terminal)

$ ./a.out

c
0987654321
arumimak
$

0 コメント:

コメントを投稿