演習 2-10

無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。

演習 2-10
if-else の代わりに条件式を使って、大文字を小文字に変換する関数 lower を書き直せ。


Exercise 2-10
Rewrite the function lower, which converts upper case letters to lower case, with a conditional expression instead of if-else.


元のコードの条件式 c >= 'A' && c <= 'Z''A' <= c <= 'Z' と読めるようにちょっとアレンジした。

#include <stdio.h>

/* Answer */
int lower(int c)
{
  return ('A' <= c && c <= 'Z') ? c + 'a' - 'A' : c;
}

int main(void)
{
  char str[] = "The C Programming Language SECOND EDITION";
  
  int i;
  for (i = 0; str[i] != '\0'; i++)
    printf("%c", lower(str[i]));
  putchar('\n');
  
  return 0;
}