How to print array with constant row space in C#? - c#

I am trying to print a jagged array with a some kind of 'constant row spacing' to make it more clear to read. Here's default output which I receive :
And I wish to receive something similar to this :
Here is my array printing code :
for (int i = 0; i < level; i++)
{
for (int j = 0; j < level; j++)
Console.Write(string.Format("{0} ", matrix[i][j].ToString("0.00")));
Console.Write(Environment.NewLine + Environment.NewLine);
}
Any quick and simple way to reach this?

Here's an example for padding with width of 5 to the left
string.Format("{0:-5}", matrix[i][j].ToString("0.00"))
You can see here more options how you can pad with spaces

Related

Printing square with non repetitive character

I want to print a rectangle like this :
&#*#
#*#&
*#&#
#&#*
But problem is that i can't find the algorithm to print this.
I only know how to print a simple rectangle/square
public static void Main(string[] args)
{
Console.Out.Write("Saisir la taille : ");
int taille = int.Parse(Console.In.ReadLine());
int i;
int j;
for(i = 0; i < taille; i++){
for(j = 0; j < taille; j++){
Console.Write("*");
}
Console.WriteLine("");
}
}
Thank you !
First things first unless you need your iterators outside of your loop, just declare them in the for declaration
public static void Main(string[] args)
{
Console.Out.Write("Saisir la taille : ");
int taille = int.Parse(Console.In.ReadLine());
for(int i = 0; i < taille; i++){
for(int j = 0; j < taille; j++){
Console.Write("*");
}
Console.WriteLine("");
}
}
Second you'll need a list of the characters you want to use, given your example
char[] chars = { '&', `#`, `*`, '#' };
and we'll need a way to know which character we want to use at any given time, say an iterator we can call characterIndex for simplicity. We will increment it each iteration. If incrementing it puts it out of the range of our character array, if characterIndex == 4, we set it back to zero.
int characterIndex;
To get the scrolling effect you have, before each line we must select a characterIndex that is offset by the row
characterIndex = i % chars.Length;
Tying it all together
public static void Main(string[] args)
{
char[] chars = { '&', `#`, `*`, '#' };
int characterIndex;
Console.Out.Write("Saisir la taille : ");
int taille = int.Parse(Console.In.ReadLine());
for(int i = 0; i < taille; i++){
characterIndex = i % chars.Length;
for(int j = 0; j < taille; j++){
Console.Write(chars[characterIndex]);
characterIndex++;
if(characterIndex == chars.Length)
characterIndex = 0;
}
Console.WriteLine("");
}
}
Getting the permutations by nesting for loops will only work if you know exactly how many elements there will be. Basically you need to write a for-loop for every element after the 1st.
The proper way to deal with this is Recursion. While there are cases where Recursion and nested for-loops are interchangeable. And in cases where they are, for loops have a potential speed advantage. While normally the speed rant applies to such differences, with the sheer amount of data both Recursion and Loops might have to deal with, it often maters - so best to prefer loops where possible.
Permutations is AFAIK not a case where loops and recursion are interchangeable. Recurions seems to be mandatory. Some problem as simply inherently recursive. As the recursion version is fairly well known, I will not post any example code.
You should defiitely use Recursion. With your example code I basically asume you are:
In a learning environment
You just learned recursion
A input variant recurions can effortless solve (like a 6 or 20 size input), is the next assignment

Align numbers in RichTextBox

I want to print a multiplication table in C# but it's not aligned!
When we type a number "n" in textbox means: n*n table.
What can I do?
for (int i = 1; i <= Convert.ToInt32(textBox1.Text); i++)
{
for (int j = 1; j <= Convert.ToInt32(textBox1.Text); j++)
{
richTextBox1.Text += Convert.ToString(i * j) + " ";
}
richTextBox1.Text += "\n";
}
Set the font of RichTextBox to the monospaced font Courier New, then add the text to RichTextBox using String.Format and setting alignment for the result of multiplication. Use a positive number to align right and use a negative number to align left:
var n = 5;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
this.richTextBox1.AppendText(string.Format("{0,3}", i * j));
}
this.richTextBox1.AppendText(Environment.NewLine);
}
Instead of format the result by {0,3} you can use below code to format based on maximum length of characters is a number which belongs to n*n:
Left Aligned:
string.Format("{0,-" +((n*n).ToString().Length + 1).ToString() +"}", i * j)
Right Aligned:
string.Format("{0," +((n*n).ToString().Length + 1).ToString() +"}", i * j)
If you want to align using spaces, you need to use a monospaced font (like Courier, or Consolas), otherwise you can use tabs: numbers won't be aligned this way though, and since numbers in your routine can get considerably big, you may end up having your numbers occupy more than the tab separation, and will get inconsistencies in the alignment if that happens.
As a general rule, if you want to align any kind of text box, go with a monospaced font.
You can pad with spaces, using, for example, String.PadLeft or String.PadRight.
This would be as simple as changing:
richTextBox1.Text += Convert.ToString(i * j) + " ";
With
richTextBox1.Text += Convert.ToString(i * j).PadLeft(5);
However this would assume all numbers are at maximum 5 characters in width.
For your precise routine, you could calculate the maximum width though, so you'd end up with something like:
// convert your input only once
int myNumber = Convert.ToInt32(textBox1.Text);
// pad with the maximum possible length, plus one space
int padAmount = (myNumber * myNumber).ToString().Length + 1;
for (int i = 1; i <= myNumber; i++)
{
for (int j = 1; j <= myNumber; j++)
{
// pad your input by the amount of spaces needed to fit all possible numbers
richTextBox1.Text += (i*j).ToString().PadLeft(padAmount);
}
}
// use Environment.NewLine instead of `\n`
richTextBox1.Text += Environment.NewLine;
Here's a fiddle. It's (for obvious reasons) for console, so in my fiddle the input number is fixed (it's in myNumber) and the output is just a string (instead of richTextBox1.Text), but it should show how it works.
Although I've made a few changes (I only convert the input number once, and use Environment.NewLine instead of \n), this is far from optimal though, you should build your string (using a StringBuilder) and assign it at once, instead of adding to the Text property. I've made a fiddle with this approach, and memory consumption has gone down by over 30mb (to just a handful of kb) just by using StringBuilder.
I think the best solution is using a tab instead of a special font and padding with white spaces.
For tabs you must add a "\t" after every number. The "\t" will be evaluated as an tab-character.
for (int i = 1; i <= Convert.ToInt32(textBox1.Text); i++)
{
for (int j = 1; j <= Convert.ToInt32(textBox1.Text); j++)
{
richTextBox1.Text += Convert.ToString(i * j) + "\t "; //here at the end
}
richTextBox1.Text += "\n";
}
But it is important, that a tab has a fixed width. In case your numbers are too long, you need 2 tabs for short numbers. But for small tables like yours it is no problem.
You can change the position of the tabs with the SelectionTabs property:
this.richTextBox1.SelectionTabs = new[] { 20, 40, 60, 80 };
BTW, you should use a StringBuilder to concatenate multiple string parts to one. And it would be more effective to parse the number from textBox1 only once and not during every iteration.
var sb = new StringBuilder(); //In namespace System.Text
var x = Convert.ToInt32(textBox1.Text); //parse only once
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= x; j++)
{
sb.Append(Convert.ToString(i * j));
sb.Append("\t ");
}
sb.Append("\n");
}
richTextBox1.Text += sb.ToString();

How to add first n numbers in an array c#

I have an array of velocity and I want to get an array of displacement.
To get displacement for each n,i need add speed[] from 0 to n,
So I'm trying to add first n numbers for each n in array speed[],n is the index of array start from 0.
for (i = 0; i < totalnumber; i++)
{
for (int k = 0; k < i; k++)
{
Xdis[i] += Xvelo[k];
Ydis[i] += Yvelo[k];
Zdis[i] += Zvelo[k];
}
}
the loop above works,but the problem is it takes too long(loop in loop)
my question is, is there any sum function in C# can handle this without use for loop?
like Xdis[i]=Xvelo.sum(i) or sth?
Why don't you use the results you already calculated? Instead of re-summing all the way up, just use the previous result:
for (i = 1; i < totalnumber; i++)
{
Xdis[i] = XDis[i-1] + Xvelo[i-1];
Ydis[i] = YDis[i-1] + Yvelo[i-1];
Zdis[i] = ZDis[i-1] + Zvelo[i-1];
}

C# & VS error: "make sure that the maximum index on a list is less than the list size"

I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with:
public static double LaskeMiidi(double[] luvut)
{
double ka = Keskiarvo(luvut);
double miidi = luvut[0];
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to!
{
miidi = luvut[i];
}
else
{
miidi = luvut[i + 1];
}
}
return miidi;
}
So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.
Yes, this is the problem:
for (int i = 0; i < luvut.Length; i++)
{
if (luvut[i] - ka < luvut[i + 1] - ka)
When i is luvut.Length - 1, then i + 1 will be luvut.Length - and therefore an invalid index. (For an array of length x, the valid indexes are 0 to x - 1 inclusive.) You probably want to end one iteration earlier:
for (int i = 0; i < luvut.Length - 1; i++)
That way i + 1 will still be a valid index in the array - both in the if condition and in the body of the else clause.
End your loop earlier:
for (int i = 0; i < luvut.Length - 1; i++)
This stops the loop ever getting to the point where an index would be invalid.
When i = luvut.Length -1, luvut[i + 1] will give an error as it is beyond the array bounds.
You need either:
for (int i = 0; i < luvut.Length - 1; i++)
Or else handle the luvut[i + 1] issue in another way in another If block.
Notice that when you define an array, range of items are between 0 and array.length-1. so you should write:
for (int i = 0; i < luvut.Length-1; i++)

Using a nested for loop and getting unexpected repetitions in c#

I've the following code in c# visual basic 2010:
for (int i = 7; i > 0; i--)
{
Char star = '*';
string numbers = "765432" ;
//Console.WriteLine(star);
for (int a = 0; a < i; a++)
{
Console.Write(star);
}
for (int b = 0; b < i; b++)
{
numbers.TrimEnd(numbers[numbers.Length - 1]);
Console.Write(numbers);
}
Console.WriteLine();
}
Console.ReadLine();
I was expecting the outcome:
*765432
repeated on the screen 7 times, instead I get:
*****765432765432765432765432765432
****765432765432765432765432
***765432765432765432
**765432765432
*765432
(I can't display the full outcome because it doesn't come back properly on screen but it's basically the variables star and numbers displayed 7 times on line 1, 6 times on line 2 etc. until once in line 7)
My understanding is that the a and b variables declared in the for loops should dictate how many times the for loop is entered into, why are the star and numbers variables also being written 7 times then 6 times to match the number of times the loop is entered into? Especially when they are initialised as * and 765432?
This is the problem (I suspect, anyway - it's certainly a problem):
numbers.TrimEnd(numbers[numbers.Length - 1]);
Strings are immutable in .NET. TrimEnd doesn't change the existing string - it returns a reference to a new one. As highlighted in the documentation:
This method does not modify the value of the current instance. Instead, it returns a new string in which all trailing characters found in trimChars are removed from the current string.
You'd also be better off using Substring for simplicity to "remove" the last character:
numbers = numbers.Substring(0, numbers.Length - 1);
Or indeed Remove:
numbers = numbers.Remove(numbers.Length - 1);
... although this will actually fail on the 7th iteration as the string will be empty at this point. It's not really what you were trying to achieve, but I think you need to take a step back from it and think carefully about each step in the process.
TrimEnd returns a new string, it doesn't modify the original string. You have to assign it back to number. Strings are immutable.
number = numbers.TrimEnd(numbers[numbers.Length - 1]);
Check for string length before indexing its element. In your for loop you can add the condition like:
for (int b = 0; b < i && numbers.Length > 0; b++)
No. The 'a' for loop runs, outputting that many stars, and the 'b' for loop runs next, outputting that many strings. If you just want '*765432' to repeat 7 times, you need to change
for (int a = 0; a < i; a++)
{
Console.Write(star);
}
for (int b = 0; b < i; b++)
{
numbers.TrimEnd(numbers[numbers.Length - 1]);
Console.Write(numbers);
}
To
for (int a = 0; a < 7; a++)
{
Console.Write(star);
Console.Write(numbers);
}
And take out the parent loop; that's what is giving you the incrementingly shorter lines.
This produce the output you are expecting:
for (int i = 0; i < 7; i++)
{
Char star = '*';
string numbers = "765432" ;
Console.WriteLine(star);
Console.Write(numbers);
Console.WriteLine();
}
I was expecting the outcome: *765432 repeated on the screen 7 times
You never need to use TrimEnd() and multiple for loop in this situation.
public static void Main()
{
for (int i = 7; i > 0;i--)
{
char star = '*';
string numbers = "765432";
Console.WriteLine(star + numbers);
}
Console.ReadLine();
}
output:
*765432
*765432
*765432
*765432
*765432
*765432
*765432

Categories

Resources