Search code examples
c#fizzbuzz

How do I shorten that specific code in C#?


I am a beginner C# learner. I am trying to learn through an app called SoloLearn. In the app, it wants me to replace 3 and its multiples in a series of numbers with "*". For example; the input is n number, let's say 7, the output should go "12 * 45 * 7" (without spaces) I tried this, it worked but these two "ifs" at the end make my eyes bleed.

using System;
using System.Collections.Generic;


namespace SoloLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = Convert.ToInt32(Console.ReadLine());
            
            //your code goes here
            for (int x = 1; x <= number; x++)
            {
                if (x%3==0)
                Console.Write("*");
                if (x%3==0)
                continue;
    
                {
                     Console.Write(x);   
                }
                
            }
            
        }
    }
}

I played around it a little but can't seem to find any way around it. How would you shorten these only with the content in this code given?


Solution

  • You don't need a continue statement there. Instead of two ifs you could use an if and an else, e.g.:

    for (int x = 1; x <= number; x++)
    {
        if (x % 3 == 0)
        {
            Console.Write("*");
        }
        else
        {
             Console.Write(x);   
        }
    }