Unusual Console.Write behaviour - c#

Console.Write isn't behaving as it should; I'm trying to create a class that handles drawing to specific regions of the console, and some really odd stuff's been happening. I've got no clue how to debug it.
When I throw this code in:
string output;
for (int i = 0; i < Console.WindowHeight; ++i) {
Console.SetCursorPosition(0, i);
output = "";
for (int j = 0; j < Console.WindowWidth; ++j) output += (i % 10).ToString();
Console.Write(output);
}
I get the following: http://snag.gy/LrFcU.jpg (I'm not allowed to post images because of reputation limits -.-)
Yet when I modify it like so:
string output;
for (int i = 0; i < Console.WindowHeight; ++i) {
Console.SetCursorPosition(0, i);
output = "";
// take one character away from the string
for (int j = 0; j < Console.WindowWidth - 1; ++j) output += (i % 10).ToString();
Console.Write(output);
}
I get this! http://snag.gy/jxLH8.jpg
WindowWidth is 80, WindowHeight is 25, and both buffer width and height are equal to window width and window height.
I'm resetting the cursor position every interation of the outer for loop... Why would it be omitting the first line?

The first line isn't omitted, it's just that it scrolled out of sight.
You're adding one more character in the first version, thus reaching the end of the line and putting the caret on the next line.

Related

positioning a pair of chars(*) center instead of left [duplicate]

This question already has an answer here:
C# christmas tree
(1 answer)
Closed 4 years ago.
So i am struggling with a console application. It is required the line of chars to form a tree like pattern instead of right wing triangle. Like this(3):
*
***
*****
so far i have this:
int rows = int.Parse(Console.ReadLine());
for(int i = 1; i <= rows; i++)
{
for(int x = 1; x <= i; x++)
{
Console.Write("*");
}
Console.WriteLine("\n");
}
I think you're looking for the PadLeft function. It adds spaces to your string on the left side, so you can position it correctly. Also, you need to multiply the amount of rows by 2 and increase the step size by 1. You'll get the following code:
int rows = int.Parse(Console.ReadLine()) * 2;
for (int i = 1; i <= rows; i += 2) {
Console.Write( "".PadLeft( (rows - i) / 2) );
for(int x = 1; x <= i; x++) {
Console.Write("*");
}
Console.WriteLine();
}
Also, if you really want to make your triangle look like this, you might need to remove this line:
Console.WriteLine("\n");
... and change it to this:
Console.WriteLine();
(This will remove the unnessecary newline, WriteLine already prints a newline).

C# and negative array indices

I'm having a problem with getting this code (from Rosetta Code) to work as part of a greater Windows Form Project:
It's a plain old insertion sort. Where it's going wrong is the bit involving the second for loop (The numbers generate just fine), in the sorting part of it. To me within a couple of iterations of the loop then j will be into negative figures and whilst other languages such as Javascript and Pascal don't seem to mind this...C# isn't happy.
private void button3_Click(object sender, EventArgs e)
{
int i, j, k;
int[] a = new int[12];
Random randomObject = new Random();
ClearOutputs(); // this is an event which just clears the
text
from the text boxes.
//Generate some random numbers
for (i = 0; i < a.Length; i++)
{
a[i] = randomObject.Next(1, 1000);
textBox1.AppendText(a[i].ToString() + "\n");
}
for (i = 1; i <= a.Length; i++)
{
k = a[i];
//*******************
for (j = i; j > 0 & k < a[j - 1]; j--)
{
a[j] = a[j - 1];
a[j] = k;
}
}
// ***************
//Display them...it never executes this part.
for (i = 0; i < a.Length; i++)
{
textBox2.AppendText(a[i].ToString() + "\n");
}
}
The longer term fix would be for me to understand the coding of the algorithm...and then fix it for myself, but if anyone could point me in the right direction...I've tried setting the 'for' loop at a higher initial value and yet still got the same "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" Any help would be greatly appreciated.
Following the provided Rosetta Code algorithm, you should change the second "for" block to:
for (i = 1; i < a.Length; i++)
{
k = a[i];
for (j = i - 1; j >= 0 && a[j] > k; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = k;
}

Multidimensional array initialization c#

I have a problem initializing the following array
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
}
when I try entering input like this
....
####
####
##..
It only take the first 3 lines not all the fourth , so any help please ?
You're using Console.Read() to read an individual character entered, but when you hit enter, Read() will return either:
A single linefeed character (\n, or decimal 10) if you're on a *nix-like platform;
A carriage-return character (\r, or decimal 13) if you're on Windows. The Read() call directly subsequent to this will then return a linefeed character.
A small modification to get the code you've got to work the way you expect:
char[,] omar = new char[4, 4];
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
omar[i, j] = (char)(Console.Read());
}
Console.Read();
if (Environment.NewLine.Length > 1)
Console.Read();
}

printing matrix square shape c#

I have an 8*8 matrix and here is my code:
static void Main(string[] args)
{
const int matrix_rows = 8;
const int matrix_columns = 8;
double[,] matrix = new double[matrix_rows, matrix_columns];
for (int i = 0 ; i < matrix_rows ; i++)
{
for (int j = 0; j < matrix_columns; j++)
{
Console.WriteLine(matrix[i, j]+ "\t");
}
Console.WriteLine("\n");
}
Console.ReadKey();
I want it to be printed square shape but it prints one "0" in each line. what should I do?
You write a new line each time. Do Console.Write() instead of Console.WriteLine()
It's because you're using Console.WriteLine each time in your inner loop - so every value is printed on a new line.
Also, if you replace Console.WriteLine("\n"); with Console.WriteLine(string.Empty); you won't get an extra blank line between each line.
Try this for your loop and see what you think of the output:
for (int i = 0; i < matrix_rows; i++)
{
for (int j = 0; j < matrix_columns; j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine(string.Empty);
}
Because your array is empty!
Look, you create it
double[,] matrix = new double[matrix_rows, matrix_columns];
and then print it. The default value for double is 0

Checkers Board Assistance

I'm just wondering if there is a simpler way of doing this:
for (int i = 0; i < 1; i++)
{
for (int j = 0; i < 8; j+2)
{
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}
What I'm trying to do is place checkers pieces on the actual checkers board. So this is to place the black pieces on the top.
P.S. If you could also give me some help on the bottom set of pieces(white).
Apart from fixing the loop you could otherwise explicitly place the pieces, makes it more readable
int[,] board = new[,]{{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}};
Modulo will do the trick but i think that TonyS's anwser was my first reaction and I would prefer that insteed the one shown below.
char[,] board = new char[8,8];
private void InitializeBoard()
{
string BoardRepresentation = "";
//for every board cell
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
//initialize board cell
board[i, j] = '0';
if (j <= 2)//black top
{
//Modulo is the trick
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'B';
}
}
else if (j >= 5) //white bot
{
if ((j - i) == 0 || ((j - i) % 2) == 0)
{
board[i, j] = 'W';
}
}
}
}
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
{
BoardRepresentation += board[i, j] + " ";
}
BoardRepresentation += Environment.NewLine;
}
}
You missed to tell us what exactly is it that you want to achieve. I see several big errors in your code, so I'll assume that you don't have full grasp of how for loop works. I hope it's not too presumptuous that I'm trying to explain it here
For loop
For loop is used to execute same portion of code several times. How many times it will be executed depends on conditions you set. Most often, you will see it in this format:
for (int i = 0; i < n; i++)
{
// Some code
}
This for loop executed code within the brackets ({ and }) n times. This is not only way to define a loop. More thorough definition of a loop is following:
for (<initialization>; <condition>; <afterthought>)
Initialization - You can some variables needed for looping. This is executed once before code within the loop is executed first time. This is optional, and you can leave it empty and use variable declared before in condition.
Condition - This is executed before each execution of code within the loop. If condition expression evaluates to true, loop is executed. Once loop is executed and afterthought is executed, condition is evaluated again and again until it evaluates to false. Condition is also optional. If you leave it out, in C# loop will be executed again until you break the loop in a different way.
Afterthought - This is executed each time code within the loop is finished executing. This is usually used to increment a variable on which loop depends. This is also optional.
Fixing your code
I assume you wanted to mark fields in a 8x8 matrix like in a checkerboard, although this is not stated in your question. You could do it this way:
// For each row in a board (start with 0, go until 7, increase by 1)
for (int i = 0; i < 8; i++)
{
// start coloring the row. Determine which field within the row needs
// to be black. In first row, first field is black, in second second
// field is black, in third row first field is black again and so on.
// So, even rows have black field in first blace, odd rows have black
// on second place.
// We calculate this by determining division remained when dividing by 2.
int firstBlack = i % 2;
// Starting with calculated field, and until last field color fields black.
// Skip every second field. (start with firstBlack, go until 7, increase by 2)
for (int j = firstBlack; j < 8; j += 2)
{
// Color the field black (set to 2)
board[i][j] = 2;
}
}
You can see my comments inline.
Big errors in your code
// This loop would be executed only once. It goes from 0 to less than 1 and is increased
// after first execution. You might as well done it without the loop.
for (int i = 0; i < 1; i++)
{
// This doesn't make sense, because you use i in condition, and initialize
// and update j.
// Also, you are trying to update j, but you are not doing so. You are not
// assigning anything to you. You should do j+=2 to increase by two. Or you
// can do j = j + 2
for (int j = 0; i < 8; j+2)
{
// I didn't really understand what you were trying to achieve here
board[ i, j ] = 2;
board[( i + 1 ), j ] = 2;
board[( i + 2 ), j ] = 2;
}
}

Categories