Recently I had gone for an C# interview and the interviewer asked me to write fizz buzz logic. Fizz buzz logic goes as follows:-
1. Print numbers from 1 to 50.
2. Print "Fizz" if divisible by 3.
3. Print "Buzz" if divisible by 5.
4. Print "FizzBuzz" if divisble by both 3 and 5.
I referred this video from youtube
https://www.youtube.com/watch?v=OX5TM3q-JQg to understand how to write FizzBuzz logic.
Below is the source code with proper comments. The basic idea I used to detect if the number divisible by 3 or 5 is by checking if remainder is zero.
{
// fizz and buzz program
for (int x = 1; x <= 50; x++) // loop through the for
{
String results = "";
if (x % 3 == 0) results = "fizz"; // remainder 0 so divi. by 3
if (x % 5 == 0) results = results + "buzz"; //remainder 0 so div by 5
if (results.Length == 0) results = x.ToString();// object convert
Console.WriteLine(results);// displays the output:
}
Console.ReadLine(); // hold the screen if any btn are not enter.
}