Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

Wednesday, 2 August 2017

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:
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);
        }
}
Output:
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

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook