LoginSignup
0
2

More than 3 years have passed since last update.

多言語で Fizz Buzz !

Last updated at Posted at 2021-03-01

はじめに

この記事では、FizzBuzzゲームのプログラミングコードを紹介する。とりあえず、Python、Fortran、C++で書いたコードを2つずつ見てみよう。

目次

1.そもそもFizzBuzzゲームとは?
2.Python
3.Fortran
4.C++

そもそも FizzBuzzゲームとは?

Python

for文
for i in range(1, 101):
    if i % 15 == 0:
        print('Fizz Buzz')
    elif i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)
while文
i = 1
while i < 101:
    if i % 15 == 0:
        print('Fizz Buzz')
    elif i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

    i += 1

Fortran

条件分岐とループによるプログラム
! fizzbuzz.f90
! G95でコンパイル
! Fortran90/95では、複数行コメントは非サポート

program fizzbuzz
  implicit none
  integer i
  do i = 1, 100
    ! iが3の倍数かつ5の倍数
    if (mod(i, 3) == 0 .and. mod(i, 5) == 0) then
      print *, "FizzBuzz"
    ! iが3の倍数(かつ、5の倍数でない)
    else if (mod(i, 3) == 0) then
      print *, "Fizz"
    ! iが5の倍数(かつ、3の倍数でない)
    else if (mod(i, 5) == 0) then
      print *, "Buzz"
    ! iが3の倍数でも5の倍数でもない
    else
      print *, i
    end if
  end do
end program fizzbuzz
サブルーチンの再帰呼び出しによるプログラム
! fizzbuzz_rc.f90
! G95でコンパイル
! Fortran90/95では、複数行コメントは非サポート

program fizzbuzz_rc
  implicit none
  call fizzbuzz(100)
contains
  recursive subroutine fizzbuzz(n)
    integer n

    if (n > 1) then
      call fizzbuzz(n-1)
    end if

    ! nが3の倍数かつ5の倍数
    if (mod(n, 3) == 0 .and. mod(n, 5) == 0) then
      print *, "Fizz,Buzz"
    ! nが3の倍数(かつ、5の倍数でない)
    else if (mod(n, 3) == 0) then
      print *, "Fizz"
    ! nが5の倍数(かつ、3の倍数でない)
    else if (mod(n, 5) == 0) then
      print *, "Buzz"
    ! nが3の倍数でも5の倍数でもない
    else
      print *, n
    end if
  end subroutine
end program fizzbuzz_rc

C++

条件分岐とループによるプログラム
/*
  fizzbuzz.cpp
*/

#include <iostream>

using namespace std; 

int main()
{
  for (int i = 1; i <= 100; i++) {
    if (i % 3 == 0 && i % 5 == 0)  // iが3の倍数かつ5の倍数
      cout << "Fizz,Buzz" << endl;
    else if (i % 3 == 0)  // iが3の倍数(かつ、5の倍数でない)
      cout << "Fizz" << endl;
    else if (i % 5 == 0)  // iが5の倍数(かつ、3の倍数でない)
      cout << "Buzz" << endl;
    else  // iが3の倍数でも5の倍数でもない
      cout << i << endl;
  }

  return 0;
}
関数の再帰呼び出しによるプログラム
/*
  fizzbuzz_rc.cpp
*/

#include <iostream>

using namespace std; 

void fizzbuzz(int n)
{
  if (n > 1) 
    fizzbuzz(n-1);

  if (n % 3 == 0 && n % 5 == 0)  // nが3の倍数かつ5の倍数
    cout << "Fizz,Buzz" << endl;
  else if (n % 3 == 0)  // nが3の倍数(かつ、5の倍数でない)
    cout << "Fizz" << endl;
  else if (n % 5 == 0)  // nが5の倍数(かつ、3の倍数でない)
    cout << "Buzz" << endl;
  else  // nが3の倍数でも5の倍数でもない
    cout << n << endl;
}

int main()
{
  fizzbuzz(100);

  return 0;
}
0
2
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
0
2