FizzBuzz In C#

“FizzBuzz” is an interview question asked during interviews to check logical skills of developers.
For Demonstration, we will print number starting from 1 to 100. When a number is multiple of three, print “Fizz” instead of a number on the console and if multiple of five then print “Buzz” on the console. For numbers which are multiple of three as well five, print “FizzBuzz” on the console.
 
 
 
Let’s try (There are several methods to create a FizzBuzz program),

Method 1
  1. for (int i = 1; i <= 100; i++)  
  2. {  
  3.         if (i % 3 == 0 && i % 5 == 0)  
  4.         {  
  5.             Console.WriteLine("FizzBuzz");  
  6.         }  
  7.         else if (i % 3 == 0)  
  8.         {  
  9.            Console.WriteLine("Fizz");  
  10.         }  
  11.         else if (i % 5 == 0)  
  12.         {  
  13.            Console.WriteLine("Buzz");  
  14.         }  
  15.         else  
  16.         {  
  17.             Console.WriteLine(i);  
  18.         }  
  19. }  
Preview

 
Method 2
  1. for (int i = 1; i <= 100; i++)  
  2. {  
  3.         string str = "";  
  4.         if (i % 3 == 0)  
  5.         {  
  6.             str += "Fizz";  
  7.         }  
  8.         if (i % 5 == 0)  
  9.         {  
  10.             str += "Buzz";  
  11.         }  
  12.         if (str.Length == 0)  
  13.         {  
  14.             str = i.ToString();  
  15.         }  
  16.         Console.WriteLine(str);  
  17.   
  18. }  
Preview

 
Hope this will help you.

Thanks. 
Ebook Download
View all
Learn
View all