# Displaying digits from 1 to 100 in C # so that each line ends with modulo 10

I am starting to learn C #, I have this code

``````static void Main(string[] args)
{
int a = 0;
while (a < 100)
{
a = a + 1;
if ((a % 10) == 0)
{
Console.WriteLine(a);
}
else
{
Console.Write(a);
Console.Write(",");
}
}
}
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Is there a more efficient way to write this code? I feel like there might be a better way to do this in C #. This is my very first code. I would be grateful for your answer. Thanks to

+3

source to share

3 answers

the short version would look like this:

``````int stepSize = 10;

for (int i = 1; i < 100; i+=stepSize )
{
Console.WriteLine(String.Join(",", Enumerable.Range(i, stepSize)));
}
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Explanation:

You walk in increments of 10 through your cycle. at each step, the   Enumerable.Range method creates an array that contains the numbers listed from the initial value ( `i`

) to the value of count ( `10`

).

The String.Join method takes each element of this array and concatenates them into a string separated by`,`

Since this looks like homework:

You should investigate how to use String.Format . This way you can arrange items on one line at specific positions.

For iterations with a counter variable, the for-loop is preferred as it is precisely made for it with a clearly readable head signature.

You've actually written very readable code, which is efficient in my opinion. Reducing the code lines does not make it necessary more efficient or faster or more readable. Sometimes the only advantage is that it looks a little more elegant;) that everything

EDIT:

You can even bring it down to one line:

``````Console.WriteLine(Enumerable.Range(0, 10).Select(x => String.Join(",", Enumerable.Range(x * 10 + 1, 10))));
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

short but awful to read and understand :)

+6

source

The first step will be used instead of a loop.

``````for(int i = 0; i <= 100; i++)
{
if ((i % 10) == 0)
{
Console.WriteLine(i);
}
else
{
Console.Write(i);
Console.Write(",");
}
}
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

You can replace

``````Console.Write(i);
Console.Write(",");
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

from

``````Console.Write(string.Format("{0},", i));
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

or even better with

``````Console.Write(\$"{i},");
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+3

source

Another approach

``````for (var i = 1; i <= 100; i++)
{
Console.Write(i);
Console.Write(i % 10 == 0 ? Environment.NewLine : ",");
}
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+1

source

All Articles