2
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.

FizzBuzz問題をシェルプログラムで作成してみる

Posted at

はじめに

Bashプログラミングの小ネタとして作成しました。
とある事情で急ピッチで記事を書いています。
ちなみに今回第3弾となります。

FizzBuzzとは

FizzBuzzに関してはこちらを確認ください。
1から順にカウントアップし、

  • 3で割り切れるときは「Fizz」を表示
  • 5で割り切れるときは「Buzz」を表示
  • 両方で割り切れるときは「FizzBuzz」を表示

といったことをします。

ソース

# !/bin/bash

echo -n "Please input number => "
read num

for i in $(seq 1 ${num})
do
  if (( $i % 3 == 0 && $i % 5 == 0 ))
  then
    echo "FizzBuzz"
  else if (( $i % 3 == 0))
    then
      echo "Fizz"
    else if (( $i % 5 == 0 ))
      then
        echo "Buzz"
      else
      echo $i
      fi
    fi
  fi
  sleep 1
done

実行結果

$ ./fizzbuzz.sh
Please input number => 15
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

終わりに

3の倍数と3の文字列があるときにahoになるプログラムを応用させれば作れますね。

このプログラムを作成することで

  • アルゴリズム
  • 条件式
  • 条件演算子
  • readコマンド

が理解できました。

2
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
2
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?