“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:
Output:
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:
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
|
Method 2:
for (int i = 1; i <= 100; i++)
{
string str = "";
if (i % 3 == 0)
{
str += "Fizz";
}
if (i % 5 == 0)
{
str += "Buzz";
}
if (str.Length == 0)
{
str = i.ToString();
}
Console.WriteLine(str);
}
|
Output:
Hope this will help you.
Thanks
0 comments:
Post a Comment