Advertisement
pcwizz

FizzBuzz with inline ifs

Oct 13th, 2014
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. /*
  2. FizzBuzz for the modern age.
  3. Plays the age old classic game fizzbuzz between 1 and 100.
  4. The rules are as follows.
  5. If a number is a multiple of 3 then print "Fizz".
  6. If a number is a multiple of 5 then print "Buzz".
  7. If a number is a multiple of both 3 and 5 then print "FizzBuzz".
  8. If a number is not a multiple of 3 nor a multiple of 5 print the
  9. number.
  10. Each out put should be on a new line.
  11.  
  12. This example requires c++11 or higher, due to the use of to_string,
  13. although it could be simply adapted to work with older standards.
  14. The example also makes use of in-line if statements, this may or not
  15. be favoured by everyone, but I like them.
  16.  
  17. Copyright (c) 2014 Morgan Hill <morgan@pcwizzltd.com>
  18.  
  19. This program is free software: you can redistribute it and/or modify
  20. it under the terms of the GNU General Public License as published by
  21. the Free Software Foundation, either version 3 of the License, or
  22. (at your option) any later version.
  23.  
  24. This program is distributed in the hope that it will be useful,
  25. but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  27. GNU General Public License for more details.
  28.  
  29. You should have received a copy of the GNU General Public License
  30. along with this program.  If not, see <http://www.gnu.org/licenses/>.
  31.  
  32. */
  33. #include <iostream>
  34. #include <string>
  35.  
  36. using namespace std;
  37. int main (){
  38.     for (int i = 1; i<=100; ++i){
  39.         string output = "";
  40.         output += i % 3 == 0 ? "Fizz":"";
  41.         output += i % 5 == 0 ? "Buzz":"";
  42.         output += output.length() == 0 ? to_string(i):"";
  43.         cout << output << endl;
  44.     }
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement