1

I am trying to write a program for C# that involves looping from 1 to 100. If there is a multiple of 3 write "Fizz" next to number, multiple of 5 write "Buzz" next to number, for both write "FizzBuzz".

I have the code but it is repeating numbers, example: 1 2 3Fizz 3 4 5Buzz 5 6Fizz 6 etc. How do I keep the numbers from repeating?

static void Main(string[] args)
{
    PrintNumbers();
    Console.ReadLine();
}

static void PrintNumbers()
{
    for (int i = 1; i <= 100; i++)
    {
        if ( i % 3 == 0)
        {
            Console.WriteLine(i + " Fizz");
        }
        if (i % 5 == 0)
        {
            Console.WriteLine(i + " Buzz");
        }
        if (i % 3 == 0 && i % 5 == 0)
        {
            Console.WriteLine(i + " FizzBuzz");
        }
        else
        {
            Console.WriteLine(i);
        }
    }
}
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
johnster
  • 63
  • 2
  • 8
  • Since you have to ALWAYS write the number, you should remove the condition on the last statement `Console.WriteLine(i)` and in turn remove the i variable from all other console writes. – user2651804 May 01 '16 at 22:08
  • Additionally you have a logical error in that any numbers being a multiple of 3 AND 5 will write: `15Fizz15Buzz15FizzBuzz`. You should simply remove the third check for `divisble by 3 AND 5` since you have already checked for both of those. – user2651804 May 01 '16 at 22:10

2 Answers2

6

Something like...

static void PrintNumbers()
{
    for (int i = 1; i <= 100; i++)
    {
        if (i % 3 == 0 && i % 5 == 0)
        {
            Console.WriteLine(i + " FizzBuzz");
        }
        else if ( i % 3 == 0)
        {
            Console.WriteLine(i + " Fizz");
        }
        else if (i % 5 == 0)
        {
            Console.WriteLine(i + " Buzz");
        }           
        else
        {
            Console.WriteLine(i);
        }
    }
}
Scott McKeand
  • 540
  • 1
  • 4
  • 15
-1

//Using VisualStudio 2022 :)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ex8
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int total = 100;
            for (int i = 1; i <= total; 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);
                }
            } 
        }
    }
}
Ay1
  • 1
  • 1
  • 1
    Please add a application type like `.NET6 Console App`, because the `VisualStudio 2022` is a `IDE` not a `Program` – HsuTingHuan Oct 16 '22 at 06:57