public static void Main()
{
int i, j;
Console.Write(" ");
for (i = 1; i < 10; i )
Console.Write(String.Format("{0,3:d}", i));
Console.WriteLine();
for (i = 0; i < 32; i )
Console.Write("=");
Console.WriteLine();
for (i = 1; i < 10; i )
{
Console.Write(i " | ");
for (j = 1; j < 10; j )
Console.Write(String.Format("{0,3:d}", i * j));
Console.WriteLine();
}
Console.ReadKey();
}
Some person did show me this piece of code and told that Any programmer, systems engineer, or systems mathematician who has seriously studied C# should know the answer
.
I don't see anything too wrong with it.
It has table limits hardcoded (10), but the table itself is for 9 numbers only, so this is not a crime.
Doing
i " | "
is not very nice for performance and memory usage, but this is such trivia.
The person does not respond to me what's was wrong with this code, I can't sleep now thinking about it!
CodePudding user response:
This question might be better asked here: Code review
- Correctness: it behaves correctly
- Readability: simple program, not too bad
- Efficiency: not too bad either
- Flexibility: poor - I suggest implementing a more generalized method which takes a table width/height parameter
- Other: String-handling is a bit archaic (can use string interpolation)
Beyond these few comments I can see a couple of reasons one might argue religiously, i.e. not about right and wrong but about "best practice" (dogma) - like use of braces
CodePudding user response:
I tried to minimize and optimize the code and add support for determining the range (min/max) of the table to be printed so that it calculates the necessary space for longer numbers.
Many programmers are allergic to the missing parentheses for single line subblocks (conditions or loops), but I'm more comfortable without them, the code is not as long and so much more readable for me. But it's more about habit. Maybe they have it as a mandatory convention in that company, but then I would have other comments on code optimization than this irrelevance.
In Python, they also just indent instead of bracket and nobody there minds.
using System;
using System.Linq;
MultipleTable(1, 9);
void MultipleTable(int min, int max)
{
int minDigits = max.ToString().Length,
maxDigits = (max*max).ToString().Length;
Console.Write(" | ".PadLeft(minDigits 3));
Console.WriteLine(String.Join(" ",
Enumerable.Range(min, max-min 1)
.Select(x => x.ToString().PadLeft(maxDigits))));
Console.WriteLine("".PadRight((max-min 1)*(maxDigits 1) minDigits 3, '='));
for (int i = min; i <= max; i )
{
Console.Write(i.ToString().PadLeft(minDigits) " |");
for (int j = min; j <= max; j )
Console.Write((i*j).ToString().PadLeft(maxDigits 1));
Console.WriteLine();
}
}
You can try it in SharpLab.