cmd doesn't show all results - c#

i'm wondering i started programming 6 monthes ago but never noticed that cmd can't show all results and it seems that there is limit. for example try this.
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(i);
}
you may not noticed at first but if you run this it only covers from 701 to 999 and you can't find 0 to 700, it seems that cmd only can show 299 lines and the previous result will be hide if you have more than that line. Am i correct? What is the problem? whats the reason for that?

Yes the command prompt has properties:
And under those properties you can adjust the default buffer higher or lower as needed:

You would need to set the buffer to the size of the loop to see all the entries.
http://msdn.microsoft.com/en-us/library/system.console.setbuffersize(v=vs.110).aspx
e.g.
Console.SetBufferSize(80, 1000);

You need to adjust the Console.BufferHeight property (see msdn).
Console.BufferHeight = 1200; //set the bufferheight to 1200 lines
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(i);
}

Related

Why does this nested loop output starts at 8 and 18?

I don't understand why this loop starts at 8 and 18 when I output it, but when I try "i < 10 and j < 10", it starts at 2 and 2. Can someone explain this to me?
class Program
{
static void Main(string[] args)
{
for (int i = 2; i < 100; i++)
{
for (int j = 2; j < 100; j++)
{
Console.WriteLine("i = {0} and j = {1}", i, j);
}
}
}
}
Screenshot of my issue:
It is because you exceed the number of lines that your console is set to display at once.
The property is called Console.BufferHeight.
Try writing Console.WriteLine(Console.BufferHeight); to see the number of lines your console is set to display at once.
You can change it simply by writing setting it to your desired value, e.g. Console.BufferHeight = 20000; or changing the settings of the console by accessing the properties in the manner, that #Greg elaborated on.
Are you sure that it isn't starting at i = 2 and j = 2? You are running this loop so many times that your console output may not show that it starts at 2,2, even though it does. Try setting a breakpoint in the second for loop, I think you'll see it is starting at 2, 2. That's because the buffer size is too small.
Here's what you can do:
Run your project.
Right-click on the title bar-> Properties-> Layout.
Set your height to something really large.
You can refer to this question for more.

c# for loop is entering without meeting its condition

So, I have this for loop:
double spec = 0, tot = 0;
for (int i = 0; i < omega_algo.Length; i++)
{
if (omega_algo[i] > 0)
spec = Math.Sqrt(omega_algo[i]);
else
spec = 0;
tot += spec;
}
Where myArray.Length = 50.
I get an IndexOutOfRangeException while debugging and see that i is 50.
So, the for loop is entering when it shouldn't ( i < myArray.Length is false )!
This exception only occurrs ocasionally, which makes it even more weird.
Does someone have an explanation/fix for this? Am I missing something or could this be a weird Visual Studio bug?
EDIT:
I've edited the for loop to show the code.
No i is being incremented and omega_algo array is not changing at all.
EDIT:
Based on the comments below, I wrote a sample app, and your code should work as is.
If your array really does have a length of 50, then the value of i will never be 50. The only way this would be possible is if you are changing the value of i inside the loop.
Can you provide more code to show some context of how/where this is being used? How the array is being defined etc?
Your code should work if executed on a single thread. Do you have any thread or asynchrone jobs that are editing the array?
If so, just lock the array before accessing it and before editing it.
lock(myArray)
{
for (int i = 0; i < myArray.Length; i++)
{
int someVar = myArray[i]; //this is where exception is thrown when i=50
}
}
EDIT:
Since omega_algo array is not changing at all, this is not a threading issue.

Modulus usage when dealing with odd numbers

I have a list of roughly 50~60 items that I want to be able to divide into multiple columns dynamically. I'm using a nested for loop and the lists divide properly when there are an even number of items. However, when there are an odd number of items the remainder (modulus) items get left out. I've been playing around with it for a while and have not struck gold yet. I'm hoping someone smarter than me can & will assist.
Thanks.
for (int fillRow = 0; fillRow < numOfCols; fillRow++)
{
for (int fillCell = 0; fillCell < (siteTitles.Count / numOfCols); fillCell++)
{
linkAddress = new HyperLink();
linkAddress.Text = tempSites[fillCell].ToString();
linkAddress.NavigateUrl = tempUrls[fillCell].ToString();
mainTbl.Rows[fillCell].Cells[fillRow].Controls.Add(linkAddress);
}
}
Well yes, the problem is here:
fillCell < (siteTitles.Count / numOfCols)
That division will round down, so for example if there are 13 titles and numOfCols is 5, it will give 2 - which means that items 10-12 won't be used.
I suggest that actually you loop over all the items instead, and work out the row and column for each item:
for (int i = 0; i < siteTitles.Count; i++)
{
int row = i / numOfCols;
int col = i % numOfCols;
// Fill in things using row, col and i
}
(It's not exactly clear what you're doing as you're using siteTitles in the loop condition and tempSites in the loop body, and you're not using fillRow when extracting the data... basically I think you've still got some bugs...)

Adding numbers from 1 to N in C#

I'm writing code in C# and trying to add all of the numbers between the number 1 and N, N being the number that is inputted in a textbox. I'm doing this, at least trying to do this, by putting it into a while loop.
I have added all the numbers between 2 textboxes before but for some reason I'm driving myself crazy and can't figure this out. I'm a beginning programmer so please be gentle.
Any help would be greatly appreciated.
Edit:
One of the six thousand things I've tried. I think this has me in an infinite loop?
private void btnAddAll_Click(object sender, EventArgs e)
{
int n;
int count = 0;
int answer = 0;
n = int.Parse(txtNum.Text);
count = n;
while (count >= 1)
{
answer = answer + count;
count++;
}
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
Why not use Gauss formula. (N*(N+1))/2
private void btnAddAll_Click(object sender, EventArgs e)
{
int n, answer;
n = int.Parse(txtNum.Text);
answer = (n*(n+1))/2;
lstShow.Items.Add("Sum = " + answer);
lstShow.Text = answer.ToString();
}
If you change the ++ to a -- it should work as you want it to.
int n;
int count = 0;
int answer = 0;
n = 3;
count = n;
while (count >= 1)
{
answer = answer + count;
count--; // here was the error
}
Console.WriteLine (answer);
Output: 6
Also, just for a point of additional interest you can use That uses Enumerable.Range and Enumerable.Sum instead of the while loop (probably goes beyond what is expected for a homework but it's useful to know what's out there).
answer = Enumerable.Range(1, n).Sum();
Your edit: you should decrement count..
Another edit, it appears I need to explain more:
By decrement I mean --. The post or pre decrement operator decreases the value by 1.
If count keeps increasing by 1, count >=1 will never be met. You need to reduce count to 1.. hence count--;
Also I suggest you use TryParse(string,out int) ; or at least wrap the Parse call in a try catch block.
Here is a pointer in pseudocode:
GetInput From User
TryParse Input
If Between 1 and N
Declare sum = 1;
for i to N-1
sum+=i;
/* if you don't want to use the for loop
while i < N
sum+=i;
inc i; */
Print sum
Debugging is an important skill for any programmer. There are some good tools in Visual Studio to help with debugging.
A good way to debug your code when you are stuck is to use 'breakpoints' and step through the code.
Select the line you want your code to stop at (e.g. n = int.Parse(txtNum.Text);) and press F9 - this will add a breakpoint at this line.
Now, when you run your programme, it will stop at the breakpoint. If you press F11, you can 'step' through the code one line at a time. You can hold your mouse over a variable to see its value while you are doing this.
You will quickly find the problem in your code if you do this.

Loop Reversal in C# Speeds Up app

We are working on a video processing application using EmguCV and recently had to do some pixel level operation. I initially wrote the loops to go across all the pixels in the image as follows:
for (int j = 0; j < Img.Width; j++ )
{
for (int i = 0; i < Img.Height; i++)
{
// Pixel operation code
}
}
The time to execute the loops was pretty bad. Then I posted on the EmguCV forum and got a suggestion to switch the loops like this:
for (int j = Img.Width; j-- > 0; )
{
for (int i = Img.Height; i-- > 0; )
{
// Pixel operation code
}
}
I was very surprised to find that the code executed in half the time!
The only thing I can think of is the comparison that takes place in the loops each time accesses a property, which it no longer has to. Is this the reason for the speed up? Or is there something else? I was thrilled to see this improvement. And would love it if someone could clarify the reason for this.
The difference isn't the cost of branching, it's the fact that you are fetching an object property Img.Width and Img.Height in the inner loop. The optimizer has no way of knowing that these are constants for purposes of that loop.
You should get the same performance speedup by doing this.
const int Width = Img.Width;
const int Height = Img.Height;
for (int j = 0; j < Width; j++ )
{
for (int i = 0; i < Height; i++)
{
// Pixel operation code
}
}
Edit:
As Joshua Suggests, putting Width in the inner loop will have you walking through the memory sequentially, which will be better cache coherency, and might be faster. (depends on how big your bitmap is).
const int Width = Img.Width;
const int Height = Img.Height;
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++ )
{
// Pixel operation code
}
}
I assume you are using the System.Drawing.Image class? Looking at the implementation of .Width and .Height I see they do a function call into GDI+ (GdipGetImageHeight and GdipGetImageWidth in gdiplus.dll), which seems to be rather expensive.
By going backwards you make that call once, rather than in every iteration.
It's not the loop reversal that speeds things up -- it's the fact that you're accessing the Width and Height properties far fewer times.
It's because the CPUs are like hockey players, they go faster when going backward ;-)
More seriously:
This is not related in the direction of the loop in any way, but rather to the fact that the in the original construct, the loop control conditions implied dereferencing the Img object to index to its Width or Height property (for each and single iteration in the loops), whereby the second construct evaluates these properties only once.
Also, the fact that the new condition tests against the value 0, saves even the loading of an immediate value.
This probably explains the difference (assuming the work done inside the inner was relatively minimal, i.e. +/- the same as work to test an Object.Property, since you indicate a roughly 50% gain).
Edit:
see Michael Stum's answer, which indicates that the Img.Width/Height reference is even more costly than thought. As it sometimes happens with properties, the implementation of the object may run a significant amount of code to produce the value (for example it may do a bunch of math to get to the width, each time, rather than somehow caching it etc..). This seems to be the case with this Img object, hence the interest to do this only once (if you are sure that the value will remain constant for the duration of the loop logic).

Categories

Resources