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(",");
}
}
}
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
source to share
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)));
}
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))));
short but awful to read and understand :)
source to share
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(",");
}
}
You can replace
Console.Write(i);
Console.Write(",");
from
Console.Write(string.Format("{0},", i));
or even better with
Console.Write($"{i},");
source to share