-2

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
oceilot
  • 11
  • 2
  • Take look at [the documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else) and you'll see that you can use a block after `if`... – sticky bit Dec 26 '20 at 23:27
  • `for (var x = 1; x <= number; x++) Console.Write(x % 3 == 0?"*": x.ToString());` – TheGeneral Dec 26 '20 at 23:41

3 Answers3

2

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);   
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

For fun:

static void Main(string[] args)
{
    int number = Convert.ToInt32(Console.ReadLine());
            
    var seq = Enumerable.Range(1, number).Select(x=>x%3==0?"*":x.ToString());
    Console.WriteLine(string.Join("", seq));
}

And I could, of course, shorten it further to a single line, but that just seems excessive. There's probably also a way to get an implicit ToString() conversion.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

The slightly shorter version of the for loop is this:

for (int x = 1; x <= number; x++)
{
    Console.Write(x % 3 == 0 ? "*" : $"{x}");
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172