I am learning the programming basics in C# and am studying the use of "for" function.
When working on an exercise I realised there's something wrong with my console - it seems as if it did not display top 6 rows.
I.e. with such a code:
for (int i = 1; i <= size; i++)
{
for (int j = 1; j <= size; j++)
{
Console.Write("{0,-3}", j);
}
Console.WriteLine();
}
Console.ReadKey();
My console spits out only smth like this:
[1
Dear masterminds, wwyd?
In order to increase the buffer size for the console as #Caius Jard suggested you need to press the right mouse button on the top console bar.
Press Properties
Change settings until you will see it will work for you. In the screenshot, you can find Windows default settings that I'm using.
You might need to re-run your program to notice some changes.
Related
For a university project I was tasked with creating a crossword game in windows forms using c#, I have 25 textboxes laid out in a grid and named with their indexes(e.g. txtCell00, txtCell01).
Image of the form layout with the textbox names and layout
To check the guesses I want to loop through all the cells and compare them to an array of the correct answers, but I don't know how to loop through all the cells without having 25 nested if statements. I wanted to know if there was a way to use string manipulation in the actual code
e.g.
for(int i = 0; i <= 4; i++)
{
for(int m = 0; m <= 4; m++){
if(txtCell[i][m].Text == ans[i][m])
{
}
}
}
I am probably being stupid and there is probably a better alternative so I would greatly appreciate any help you could give.
I have very uncanny problem about Win32 console.
There are missing pixels in the console cell like that:
Okay, let's consider the problem a little bit more detailed. I figure out the bug comes, when all of this 3 factors are available:
We must use symbol that we can see the first column of pixels is missing, so 'i' will be useless in our case, because it's printed on middle of the cell, but character like '0', or better '\u2593' (which is filling the cell fully) is going to be good choice as well:
char myChar = '\u2593';
Also need to change the Console.ForegroundColor different from our default console color. For example - Yellow:
Console.ForegroundColor = ConsoleColor.Yellow;
Finally, print symbols backward through moving the cursor position, so we're going to use at least twо times this lines:
Console.SetCursorPosition(left, 0);
Console.Write(myChar);
Now we are ready to simulate our problem with the following code:
static void Main()
{
char myChar = '\u2588';
Console.ForegroundColor = ConsoleColor.Yellow;
for (int i = 5; i >= 0; i--)
{
Console.SetCursorPosition(i, 0);
Console.Write(myChar);
Console.SetCursorPosition(i, 0);
Console.Write(myChar);
}
Console.WriteLine();
}
The problem can be observe even more clearly in this console snake game:
Here's an explanation of the previous one screenshot:
So, is it possible to get rid of this irritating effect of cracked ASCII, given that I use filling symbols, change the console colors and print backward?
The following code is not entering the i for loop. I have had problems with my computer and VS2010. Is this a coding issue (I am a vb.net programmer programing c#.net) or a vb install issue?
for(int hi = 1; hi > 10; hi++)
{
reply = pingsender.Send(ip, 500, buffer, options);
avgtime += reply.RoundtripTime;
}
//EDIT:
//All code except for issue taken offline due to company policy
//sorry for any inconvience
This code is nested in four for loops (that all work) and is runnin, and is meant to put ping statistics in a list box. Sorry for the messy code, I comment and clean after I get the code working.
Thank you in advance for all of your hard work!
for(int hi = 1; hi > 10; hi++)
will never be true; fails at the first test, as 1 is not > 10.
The middle clause is (essentially) "while" - not "until". I suspect you need < 10 (for 9 iterations) or <= 10 (for 10 iterations).
It's hard to guess why the code isn't entering your for loop. (Especially since the code is just a snippet of the problem.)
I'd suggest that you place a breakpoint on your for loop, then check what the variables are set to. It's always helpful to use your debugger for diagnosis.
Cheers!
i am creating project in c#.net. my execution process is very slow. i also found the reason for that.in one method i copied the values from one list to another.that list consists more 3000values for every row . how can i speed up this process.any body help me
for (int i = 0; i < rectTristrip.NofStrips; i++)
{
VertexList verList = new VertexList();
verList = rectTristrip.Strip[i];
GraphicsPath rectPath4 = verList.TristripToGraphicsPath();
for (int j = 0; j < rectPath4.PointCount; j++)
{
pointList.Add(rectPath4.PathPoints[j]);
}
}
This is the code slow up my procees.Rect tristirp consists lot of vertices each vertices has more 3000 values..
A profiler will tell you exactly how much time is spent on which lines and which are most important to optimize. Red-gate makes a very good one.
http://www.red-gate.com/products/ants_performance_profiler/index.htm
Like musicfreak already mentioned you should profile your code to get reliable result on what's going on. But some processes are just taking some time.
In some way you can't get rid of them, they must be done. The question is just: When they are neccessary? So maybe you can put them into some initialization phase or into another thread which will compute the results for you, while your GUI is accessible to your users.
In one of my applications i make a big query against a SQL Server. This task takes a while (built up connection, send query, wait for result, putting result into a data table, making some calculations on my own, presenting the results to the user). All of these steps are necessary and can't be make any faster. But they will be done in another thread while the user sees in the result window a 'Please wait' with a progress bar. In the meantime the user can already make some other settings in the UI (if he likes). So the UI is responsive and the user has no big problem to wait a few seconds.
So this is not a real answer, but maybe it gives you some ideas on how to solve your problem.
You can split the load into a couple of worker threads, say 3 threads each dealing with 1000 elements.
You can synchronize it with AutoResetEvent
Some suggestions, even though I think the bulk of the work is in TristripToGraphicsPath():
// Use rectTristrip.Strip.Length instead of NoOfStrips
// to let the JIT eliminate bounds checking
// .Count if it is a list instead of array
for (int i = 0; i < rectTristrip.Strip.Length; i++)
{
VertexList verList = rectTristrip.Strip[i]; // Removed 'new'
GraphicsPath rectPath4 = verList.TristripToGraphicsPath();
// Assuming pointList is infact a list, do this:
pointList.AddRange(rectPath4.PathPoints);
// Else do this:
// Use PathPoints.Length instead of PointCount
// to let the JIT eliminate bounds checking
for (int j = 0; j < rectPath4.PathPoints.Length; j++)
{
pointList.Add(rectPath4.PathPoints[j]);
}
}
And maybe verList = rectTristrip.Strip[i]; // Removed 'VertexList' to save some memory
Define variable VertexList verList above loop.
I'm new to C#. And I would like to program something like, displaying the prime numbers in a listbox if user will input any integer in the textbox. (that means, if they write 10, it will display the prime numbers from 0-10, or 20 from 0-20, etc).
What should I consider first, before I do the programming?
I know there are many examples in the internet, but first I would like to know what will I need?
Thanks for the tip;-)
===
Thanks guys. So you're suggesting that it's better to do it first in the Console application?
I did an example of "For Loop" using Console Application a very simple one, but then when I tried to do it in the Windows Form Application, I'm not sure how to implement it.
I'm afraid that if I keep doing examples in the Console, then I'll have difficulty to do it in Windows Form Apps.
What do you think?
======
Hello again,
I need some feedback with my code:
Console.WriteLine("Please enter your integer: ");
long yourInteger;
yourInteger = Int32.Parse(Console.ReadLine());
//displaying the first prime number and comparing it to the given integer
for (long i = 2; i <= yourInteger; i = i + 1)
{
//Controls i if its prime number or not
if ((i % 2 != 0) || (i == 2))
{
Console.Write("{0} ", i);
}
}
Well, first of all I'd think about how to find prime numbers, and write that in a console app that reads a line, does the math, and writes the results (purely because that is the simplest thing you can do, and covers the same parsing etc logic you'll need later).
When you are happy with the prime number generation, then look at how to do winforms - how to put a listbox, textbox and button on a form; how to handle the click event (of the button), and how to read from the textbox and write values into the listbox. Your prime code should be fairly OK to take "as is"...
If you don't already have an IDE, then note that C# Express is free and will cover all of the above.
You'll need to know:
How to read user input from a Windows application
How to generate prime numbers within a range
How to write output in the way that you want
I strongly suggest that you separate these tasks. Once you've got each of them working separately, you can put them together. (Marc suggests writing a console app for the prime number section - that's a good suggestion if you don't want to get into unit testing yet. If you've used unit testing in other languages, it's reasonably easy to get up and running with NUnit. A console app will certainly be quicker to get started with though.)
In theory, for a potentially long-running task (e.g. the user inputs 1000000 as the first number) you should usually use a background thread to keep the UI responsive. However, I would ignore that to start with. Be aware that while you're computing the primes, your application will appear to be "hung", but get it working at all first. Once you're confident with the simple version, you can look at BackgroundWorker and the like if you're feeling adventurous.
I discussed creating prime numbers using the Sieve of Eratosthenes on my blog here:
http://blogs.msdn.com/mpeck/archive/2009/03/03/Solving-Problems-in-CSharp-and-FSharp-Part-1.aspx
The code looks like this...
public IEnumerable<long> GetPrimes(int max)
{
var nonprimes = new bool[max + 1];
for (long i = 2; i <= max; i++)
{
if (nonprimes[i] == false)
{
for (var j = i * i; j <= max; j += i)
{
nonprimes[j] = true;
}
yield return i;
}
}
}
With this code you can write statements like this...
var primes = SieveOfEratosthenes.GetPrimes(2000);
... to get an IEnumerable of primes up to 2000.
All the code can be found on CodePlex at http://FSharpCSharp.codeplex.com.
The code is "as is" and so you should look at it to determine whether it suits your needs, whether you need to add error checking etc, so treat it as a sample.
Here's a great "naive" prime number algorithm, that would be perfect for your needs:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Here is a response to the edit:
Thanks guys. So you're suggesting that it's better to do it first in the Console application? I did an example of "For Loop" using Console Application a very simple one, but then when I tried to do it in the Windows Form Application, I'm not sure how to implement it. I'm afraid that if I keep doing examples in the Console, then I'll have difficulty to do it in Windows Form Apps. What do you think?
If you want to present the prime numbers as a windows forms application then you need to design the user interface for it as well. That is a bit overkill for such a small problem to be solved. The easiest design you can do is to fill up a ListBox in your form (example).
If you're really keen on learning Windows Forms or WPF then there are several resources for this.
I was recently writing a routine to implement Sieve Of Eratosthenes and came across this thread. Just for the archives, here is my implementation:
static List<int> GetPrimeNumbers(int maxNumber)
{
// seed the master list with 2
var list = new List<int>() {2};
// start at 3 and build the complete list
var next = 3;
while (next <= maxNumber)
{
// since even numbers > 2 are never prime, ignore evens
if (next % 2 != 0)
list.Add(next);
next++;
}
// create copy of list to avoid reindexing
var primes = new List<int>(list);
// index starts at 1 since the 2's were never removed
for (int i = 1; i < list.Count; i++)
{
var multiplier = list[i];
// FindAll Lambda removes duplicate processing
list.FindAll(a => primes.Contains(a) && a > multiplier)
.ForEach(a => primes.Remove(a * multiplier));
}
return primes;
}
You could always seed it with "1, 2" if you needed 1 in your list of primes.
using System;
class demo
{
static void Main()
{
int number;
Console.WriteLine("Enter Number you Should be Checked Number is Prime or not Prime");
number = Int32.Parse(Console.ReadLine());
for(int i =2;i {
if(number % i == 0)
{
Console.WriteLine("Entered number is not Prime");
break;
}
}
if(number % i !=0)
{
Console.WriteLine("Entered Number is Prime");
}
Console.ReadLine();
}
}
Your approach is entirely wrong. Prime numbers are absolute and will never change. Your best bet is to pre-generate a long list of prime numbers. Then come up with an algorithm to quickly look up that number to determine if it is on the list. Then in your case (since you want to list all in the given range just do so). This solution will be much faster than any prime number finding algorithm implemented during run-time. If the integer entered is greater than your list then you can always implement the algorithm starting at that point.