int a, b, c;
a = 1;
b = 2;
c = a + 2*b;
for (a=1; c<15; a++)
{
Console.WriteLine(c.ToString());
}
Console.ReadLine();
I have a simple question. Do I have to define my condition depending on my initializing variable?
In the example above, I want the loop to stop when a variable "a" becomes 10, so variable "c" will be less than 15.
But the output is infinite lines of "5". I expect my output to be 14.
what am I doing wrong?
move c change inside of the loop, or you will itereate without end:
for (a=1; c<15; a++)
{
c = a + 2*b;
Console.WriteLine(c.ToString());
}
If you really wanted you could omit all 3 parts of a for loop so it essentially becomes a while(true) loop
for(;;)
So no, it doesn't need to.
But to make your program work, you'll need to update the value of c inside the loop
for (a=1; c<15; a++)
{
c = a + 2*b;
Console.WriteLine(c.ToString());
}
do i have to define my condition depending on my initializing variable?
no you don't you can define any condition you want.
what am I doing wrong?
You never so something to make this condition false it will run forever like in your case.
You change c only once before the loop starts:
c = a + 2*b;
for (a=1; c<15; a++)
{
Console.WriteLine(c.ToString());
}
as soon as you enter the loop c is never changed again! Move the changing part into the loop:
for (a=1; c<15; a++)
{
c = a + 2*b;
Console.WriteLine(c.ToString());
}
You could even write the loop using a bool variable
bool condition = true;
for (int a = 0; condition; i++)
{
c = a + 2*b;
if (c > 15)
{
condition = false;
}
}
EDIT
You could even do the computation inside the comparison block of the for-loop and it would work:
for (a = 0; (c = a + 2 * b) < 15; a++)
{
Console.WriteLine(c.ToString());
}
Disclaimer: I would not recommend it because it is cryptic and horrible to read.
A inside condition:
for (a=1; a<=10; a++)
{
c = a + 2*b;
Console.WriteLine(c.ToString());
}
Loop will stop when, c becomes 14.
Related
hello im new to programing with c# and i wanted to re-create an old proyect i made in scratch but with c#
but i have several problems with the code i wrote.
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++) ;
{
int R = qny + ADD;
for (int i = 0; i < R; i++) ;
{
string C = string.Join(C, B);
}
int qny = qny - 1;
int B = B + 1;
}
Console.WriteLine(C);
the main problem is that i cant use the variables "qny","B" and "C" inside the "for". the only one that doesnt show an error message is the "ADD" variable
its suposed to write numbers like this
qny
result
2
112
3
111223
4
1111222334
errors:
Error CS0841 Cannot use local variable 'qny' before it is declared. A variable must be declared before it is used.
Error CS0136 A local variable named 'C' cannot be declared in this scope because it would give a different meaning to 'C', which is already used in a 'parent or current/child' scope to denote something else
Error CS0165 Use of unassigned local variable 'C'
Error CS0841 Cannot use local variable 'B' before it is declared.
Error CS0136 A local variable named 'qny' cannot be declared in this scope because it would give a different meaning to 'qny', which is already used in a 'parent or current/child' scope to denote something else
Error CS0136 A local variable named 'B' cannot be declared in this scope because it would give a different meaning to 'B', which is already used in a 'parent or current/child' scope to denote something else
Your for loops end with a semicolon, which ends the loop. The following code blocks are not treated as part of the loop body because of that. Additionally as aybe mentioned you use i for both loops which will update the same variable.
EDIT: As mentioned below you also shouldn't redeclare the variable C as it won't update the variable C at the top, same reason as to why you don't want to use i for both loops.
EDIT: Code below still has redeclared variables, check author's answer for updated code.
I suggest changing it to this:
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++)
{
int R = qny + ADD;
for (int j = 0; j < R; j++)
{
C = string.Join(C, B);
}
int qny = qny - 1;
int B = B + 1;
}
Console.WriteLine(C);
To avoid such errors in the future I would recommend checking out some tutorials on the basics of C#. I wish you good luck on your coding journey!
Thanks to the people that helped me. As someone suggested, I’ll check out some tutorials. The final code looks like this:
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++)
{
int R = qny + ADD;
for (int j = 0; j < R; j++)
{
C = string.Join(C, B);
}
qny = qny - 1;
B = B + 1;
}
Console.WriteLine(C);
So I want to recreate this process with a for loop. What's the simplest way of doing this. I can do 1 to 10 but let's say you have 3 as your start value I can't get the first line to start with 3 symbols.
Thanks in advance.
Since you haven't shared any code, I'll give you an idea as to how you can print the values. I've used 2 for loops to print the value. Although there maybe better and shorter algorithms to do the same
Just edit my code below to suit your needs.
public static void Main()
{
var start = 3; //StartTextBox.Text
var end = 10; //EndTextBox.Text
var symbol = "#"; //SymbolTextBox.Text
for (var i = start; i < end; i++)
{
var toPrint = string.Empty;
for (var j = 0; j < i; j++) toPrint += symbol;
Console.WriteLine(toPrint); //LabelX.Text = toPrint;
}
Console.ReadLine();
}
You can see in the above code that if you change the value of start to any number, the value gets printed properly.
Another option assuming some of your object names...
for (int i = int.Parse(txtStart.Text); i <= int.Parse(txtEnd.Text); i++)
{
lblOutput.Text += new String(txtSymbol.Text.ToCharArray()[0], i) + Environment.NewLine;
}
I have 2 checked list boxes, where you select the main idea in the first one, and select a narrower focus in the 2nd box. After much work, I finally made it work, but it still seems horribly inefficient. Is there a way to optimize this?
List<int> k= new List<int>();
int f = 0;
for(int j = 0; j < SubRaces.Items.Count; j++) {
if(SubRaces.GetItemCheckState(j) == CheckState.Checked) {
f = j;
}
}
for(int i = 0; i < DNDSubRace.allSubRaces.Count; i++){
if(DNDSubRace.allSubRaces[i].MainRace.Name == Races.SelectedItem) {
k.Add(i);
}
}
DNDSubRace.allSubRaces [k [f]].DNDSubRaceDescription();
SubRaceBenefits.Text = DNDSubRace.allSubRaces [k [f]].Details;
You can optimize the code a little bit, for example you can add a break statement in the first for loop (this requires you to reverse the loop to get the exact same behaviour, provided SubRaces.GetItemCheckState() does not need to be called for every element)
List<int> k = new List<int>();
int f = 0;
for(int j = SubRaces.Items.Count - 1; j >= 0; j--) {
if(SubRaces.GetItemCheckState(j) == CheckState.Checked) {
f = j;
break;
}
}
for(int i = 0; i < DNDSubRace.allSubRaces.Count; i++){
if(DNDSubRace.allSubRaces[i].MainRace.Name == Races.SelectedItem) {
k.Add(i);
}
}
DNDSubRace.allSubRaces [k [f]].DNDSubRaceDescription();
SubRaceBenefits.Text = DNDSubRace.allSubRaces [k [f]].Details;
Another possibility is using Linq which will be slower, but is shorter to write. When using Linq to shorten the above solution, the result is:
List<int> k = DNDSubRace.allSubRaces.Where(r=>r.MainRace.Name == Races.SelectedItem).ToList();
int f = 0;
for(int j = SubRaces.Items.Count - 1; j >= 0; j--) {
if(SubRaces.GetItemCheckState(j) == CheckState.Checked) {
f = j;
break;
}
}
DNDSubRace.allSubRaces [k [f]].DNDSubRaceDescription();
SubRaceBenefits.Text = DNDSubRace.allSubRaces [k [f]].Details;
The first way of optimizing the code is reducing the number of cycles the upper for loop will be run for. When there are two matching elements in SubRaces then the variable f will be set to the index two times and the last match will stay (in the unoptimized version). If you reverse the for loop and exit it as soon as you get a match you will end up with the same behaviour, but it will be quicker.
The second rewrite wraps the second for loop into a Linq statement, which is slower but is shorter to write. Essentially it applies a filter and then copies the matching elements over to a new List.
I hope this helps!
Your answer would be to use events. When the item in the first list gets selected you can populate the second list with only its related options.
I currently have a (somewhat messy) bubble sort of an object array called "sorted", the code is as follows
object storage = 0;
for (int i = 0; i < sorted.Length; i++)
{
for (int c = 0; c < sorted.Length - 1; c++)
{
if (sorted[c].ToString().CompareTo(sorted[c + 1].ToString()) > 0)
{
storage = sorted[c + 1];
sorted[c + 1] = sorted[c];
sorted[c] = storage;
}
}
return sorted;
Problem is that this function always loops through the array , no matter what. Hypothetically speaking the "sorted" array could be a large array and just so happen to be sorted already, in which case the function would still scan the array and work for some time, which I want to prevent.
So the question is, how do I stop the loop properly in case the array is sorted already?
A bubble sort bubbles the largest (smallest) element of an array towards the end of an array. This is what your inner loop does.
First of all you can take advantage of the knowledge that after n iterations, the last n elements are sorted already, which means that your inner loop doesn't need to check the last n elements in the (n+1)th iteration.
Secondly, if the inner loop doesn't change anything, the elements must be in sequence already, which is a good point for a break of the outer loop.
Since you're doing this as a practising exercise, I'll leave the coding up to you :-)
Why don't you use OrderBy instead of sorting it yourself?
sorted = sorted.OrderBy(s=> s).ToArray();
If you insist to use the bubble sort, you can do this:
bool changed;
for (int i = 0; i < sorted.Length; i++)
{
changed = false;
for (int c = 0; c < sorted.Length - 1; c++)
{
if (sorted[c].ToString().CompareTo(sorted[c + 1].ToString()) > 0)
{
changed = true;
storage = sorted[c + 1];
sorted[c + 1] = sorted[c];
sorted[c] = storage;
}
if(!changed) break;
}
I'm setting changed to false each time in the first loop. If there was no changes to the end, then the array is already sorted.
Try this:
object storage = 0;
for (int i = 0; i < sorted.Length; i++)
{
bool swapped = false;
for (int c = 0; c < sorted.Length - 1; c++)
{
if (sorted[c].ToString().CompareTo(sorted[c + 1].ToString()) > 0)
{
storage = sorted[c + 1];
sorted[c + 1] = sorted[c];
sorted[c] = storage;
swapped = true;
}
}
if (!swapped)
{
break;
}
}
If it gets through a pass without swapping then the array is ordered so it will break.
If you have a for loop:
for(i=0;i<10;i++){}
Now, when i==5, how can I exit the for loop completely without using break, return, or if?
The best I could come up with was this:
for (int i = 0; i < 10; i++)
{
i = (i == 5) ? 10 : i;
Trace.WriteLine("i = " + i.ToString());
}
...which will cause the loop to run six times (i=0..5) and display this..
i = 0
i = 1
i = 2
i = 3
i = 4
i = 10
The alternative way to "exit the loop" (in a particularly nasty fashion) would be to do this...
for (int i = 0; i < 10; i++)
{
int a = 3 / ((i == 5) ? 0 : 1);
Trace.WriteLine("i = " + i.ToString());
}
..which crashes out, errr, successfully exits the loop without using the break, return or if commands.
i = 0
i = 1
i = 2
i = 3
i = 4
A first chance exception of type 'System.DivideByZeroException' occurred in MikesProgram.dll
language is C# .it was an interview question actually..curious
Do I get the job ?
I would need to check your health & dental plans, and I have to leave early on Thursdays to collect my daughters from school.
;-)
for (int n = 0; n < 10; n++)
{
n += (n / 5) * 5;
}
well here's another way if you want to break the processing exactly when i = 5 without using break, return, or if
for (int lowsetLimit = 0, highestLimit = 10, i = lowsetLimit; i < highestLimit; i++)
{
//normal code which process before i gets eqaul to 5 goes here...
i = (i < 5) ? i : highestLimit; //and here is the pivot point.
}
for(i=0;i<10;i++){
(i==5) ? goto Outer : //do something;
}
Outer:
//do something
The question says that loop should end when i=5, It says nothing about start, So this should be valid (ternary operator solution is better, but if we are not allowed to use any conditional operator)
for (int i = 0; i < 10; i++)
{
i=i-4;
Console.WriteLine("i = " + i.ToString());
i=i+4;
}
this Starts at -4 and ends at 5.
The real answer of course would be the following:
for (i=0; i!=5; i++)
{
// do something
}
But let's make it a bit more generic: stop if (expression) becomes true.
The second argument of the for loop is a boolean expression which determines whether to continue the loop with the next element or not.
So if you want to stop looping because of any condition:
for (i=0; !(expression) && i<10; i++)
{
// do something
}
This works using while and goto:
for (int i = 0; i < 10; i++)
{
while (i < 5)
{
Console.Write(i + " ");
goto OutsideWhile;
}
OutsideWhile:
continue;
}
// 0 1 2 3 4