Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So I currently have the problem that I am unable to increment my variables. Using 'i++' in my code seems to do nothing and using any other form of incrementing a value does nothing too.
static void Main(string[] args)
{
Console.WriteLine("Enter a number to see its times tables");
int number = Convert.ToInt16(Console.ReadLine());
int i;
for (i = 10; i == 10; ++i)
{
int output;
output = i * number;
Console.WriteLine(output);
}
Console.ReadKey();
}
All I am trying to do is create a basic loop but it is just stuck in an infinite loop, setting my variable 'i' to 10 causes the loop to work like its supposed to but it only executes once. The loop part becomes irrelevant.
Try
for (i = 0; i <= 10; i++)
Your condition means that the loop executed an incorrect number of times.
By incorrect number looking at your post and various attempts this means anything from zero to 'a positive' (but incorrect) number of times.
An if statement is a compound statement. In your case your if statement is composed of three sub-statements - an initialization, a test and an increment.
When the if statement is executed these three statements are executed in order.
If the test returns false the loop is not entered so when the condition is 'i==10' and the initialization is 'i=1' the loop is not executed at all. When the initialization is 'i=10' then the loop executes once.
Sub-statements 2 and 3 are executed after each execution of the content of the loop and as long as statement 2 resolves to true the loop will continue being executed.
In our example using a condition 'i <= 10' would cause the code within the loop to be executed 11 times. 'i<10' would cause it to be run ten times. Care has to be taken when choosing sub-statement 2 (i.e. the loop condition). You have to make sure that the initial value in statement 1 and the increment in statement 3 (or alternatively a change to the value made within the body of the loop itself) guarantee that the condition will eventually fail.
If not then code has to be added to the loop to ensure that the loop will exit.
This will loop indefinitely
for (int x=0; x==0; ) {
}
This will NOT loop indefinitely
for (int x=0; x==0; ) {
x++;
}
A test and break out of a loop could be done like shown in the following.
for (int x=0; x==0; ) {
if (x==0) {
break;
}
}
If you do not ensure that the loop is guaranteed to terminate it could potentially never exit.
By Using
(i = 0; i < 10; i++)
The range of i will be from 0 to 9
By using
(i = 0; i <= 10; i++)
The range of i will be from 0 to 10
By using
(i = 1; i <= 10; i++)
The range of i will be from 1 to 10
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am calculating month's days based on cmbYear & cmbMonth with the below code:
int days = DateTime.DaysInMonth(Convert.ToInt16(cmbYear.SelectedItem), Convert.ToDateTime("01-" + cmbMonth.SelectedItem + "-2011").Month);
What I am trying to achieve, using for loop, is to create a drop down list that includes all numbers starting from 1 to int days for cmbDay combo box. Below is my code which generates an error when I am trying to import the end point of the code i = days;. Error in Cannot implicitly convert type int to bool.
Any help will be appreciated.
for (int i = 1; i = days; i++)
{
}
the Loop should Looks like
for (int i=1; i <= days; i++)
or
for (int i=1; i < days; i++)
depends on what you Need.
You have to use <= instead of =
for (int i=1; i <= days; i++)
{
}
The second parameter is the condition. As long as it is true, the loop goes on
for (C# reference)
The for statement defines initializer, condition, and iterator
sections:
for (initializer; condition; iterator)
body
The condition section
The condition section, if present, must be a boolean expression. That
expression is evaluated before every loop iteration. If the condition
section is not present or the boolean expression evaluates to true,
the next loop iteration is executed; otherwise, the loop is exited.
You had i = days which is an assignment, and results in an int which is not a condition (bool).. What you probably intended was i == days which is still wrong.
What you needed was the following, which says "while i is less then days, loop the body"
for (int i=1; i < days; i++)
it's a simple syntactical error. you've misses an '<'
for(int i=1; i<=days;i++){..}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm making a dice of the Royal Game of Ur in C#. It needs 4 4-sided pyramids that have 2 out of 4 peaks colored white. This means that a single dice gives 50/50 chance of being either 0 or 1.
Now look at this code and tell me why it sometimes gives me 5 and 6.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour {
public Button rollButton;
public int result;
void Start()
{
rollButton.onClick.AddListener(onClick);
}
void resultReset()
{
Debug.Log("Setting result from " + result + " to 0");
result = 0;
}
public int Calculate()
{
for (int i = 0; i < 4; i++)
{
int num = Random.Range(0,2); // Either 1 or 0.
result = result + num; // num is added to total result
if (result > 4)
{
Debug.Log("Rolling " + result + " not possible!!");
}
}
return result;
}
void onClick()
{
resultReset();
int iRolled = Calculate();
Debug.Log("I rolled " + iRolled); // Sometimes gives 5+ and skips the for loop (like, goes 1-2 times and gives out an impossible number)
}
}
I can't reproduce this, but my best guess would be that the onClick method is tied to two different objects that are both being triggered simultaneously? Or maybe the event handler is added to a single object multiple times somehow. Either might explain why it is being fired twice. You might have a race conditions where both objects reset the [shared] result and then both start adding to it at the same time. Try running your loop against non-shared local variables instead, like this:
public int Calculate()
{
int thisRoll = 0; // only accessible from inside the method
for (int i = 0; i < 4; i++)
{
int num = Random.Range(0,2); // Either 1 or 0.
thisRoll = thisRoll + num; // num is added to total result
if (thisRoll > 4)
{
Debug.Log("Rolling " + thisRoll + " not possible!!");
}
}
return thisRoll;
}
void onClick()
{
//resultReset(); // not necessary anymore
int iRolled = Calculate();
Debug.Log("I rolled " + iRolled); // Sometimes gives 5+ and skips the for loop (like, goes 1-2 times and gives out an impossible number)
// set result here if you actually need it in addition to iRolled:
result = iRolled;
}
At least one of OnClick and Calculate is being called twice.
One time is accounted for by the call to AddListener when Unity calls Start() on ButtonScript. Any additional calls on a click would create a race condition that could produce unexpected output.
Make sure that neither of those methods are included in the button's list of On Click events in the inspector before you run the scene.
I am new to programming, and can not understand how the following code is interpreted by the compiler. As you can notice in the code, the while loop does not have curly braces around the code that comes right after it. Can somebody please explain to me, step by step, how this loop works:
int num = 0;
while(++num < 6)
Console.WriteLine(++num);
Console.WriteLine(num++);
Console.WriteLine(++num);
A while loop without braces is the same as a while loop with braces surrounding the line immediately below it:
int num = 0;
while(++num < 6)
{
Console.WriteLine(++num);
}
Console.WriteLine(num++);
Console.WriteLine(++num);
First iteration:
while(1 < 6) // num is 1
{
Console.WriteLine(2); // num is 2
}
Second iteration:
while(3 < 6) // num is 3
{
Console.WriteLine(4); // num is 4
}
Third iteration:
while(5 < 6) // num is 5
{
Console.WriteLine(6); // num is 6
}
On the fourth iteration, num becomes 7 and then gets checked by < 6, which evaluates to false. The while loop exits and the two lines below gets executed.
// num is 7
Console.WriteLine(7); // num is 8
Console.WriteLine(9); // num is 9
So it prints 2, 4, 6, 7, 9
Since ommitting curly braces can quickly lead to unexpected behavior or hard to read code, it is good practice to always write them, even if not needed. Consider the following code (I have left out the indentation on purpose):
int i, j;
for (i=0;i<10;i++)
for (j=0;j<10;j++)
if (j > i)
continue;
foo(i, j);
Nobody will be able to read that, and even if you add the spaces, it's very error prone. Also, if you later need to add another line to the if () condition, you'll very likely forget to also add braces. (The example is very poor: foo(i,j) will only be called once and the loop will do nothing!)
Also beware of the following slightly modfied code from your question:
int num = 0;
while(++num < 6); // Careful: a semicolon ends the statement
Console.WriteLine(++num);
This will run the loop six times before even calling Console.WriteLine once, because the semicolon ends the statement.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am writing C# program in Visual Studio 2010, to build a windows application.
I have created a class named Store. And inside Store class, I have created a method named StoreLength(Store ob)
public int StoreLength(Store ob)
{
int i = 0, L = 0;
while (i < 100)
{
if (ob.a[i] != null)
L += 1;
}
return L;
Now from other class I have created an object of Store class. And using that object I am trying to use the StoreLength method.
private void buttonEqual_Click(object sender, EventArgs e)
{
int l = ob.StoreLength(ob);
DisplayUnit.Text = Convert.ToString(l);
}
Now when I am running the program, everythign is working properly but as soon as I am clicking on buttonEqual, the window freezes. I think there is some problem with in buttonEqual1_Click mothod, or in StoreLength method.
Please help.
It's because the while loop's condition is always satisfied.
Every time it evaluates i, it'll always be less than 100 because you set it to 0 and its value does not change.
The typical approach would be to increment i by 1 on every iteration:
while (i < 100)
{
i++;
if (ob.a[i] != null)
L += 1;
}
The reason this causes it to freeze is because your UI is 'waiting' (in a roundabout way) for this while loop to complete.
Also, consider using a for loop for scenarios like this. It suggests the declaration, initialisation, condition and increment all on the one line for readability and consistency sake:
for(int i = 0; i < 100; i++)
{
if (ob.a[i] != null)
L += 1;
}
I have the following method:
static Random rr = new Random();
static void DoAction(Action a)
{
ThreadPool.QueueUserWorkItem(par =>
{
Thread.Sleep(rr.Next(200));
a.Invoke();
});
}
now I call this in a for loop like this:
for (int i = 0; i < 10; i++)
{
var x = i;
DoAction(() =>
{
Console.WriteLine(i); // scenario 1
//Console.WriteLine(x); // scenario 2
});
}
in scenario 1 the output is: 10 10 10 10 ... 10
in scenario 2 the output is: 2 6 5 8 4 ... 0 (random permutation of 0 to 9)
How do you explain this? Is c# not supposed to preserve variables (here i) for the anonymous delegate call?
The problem here is that there is one i variable and ten instances / copies of x. Each lambda gets a reference to the single variable i and one of the instances of x. Every x is only written to once and hence each lambda sees the one value which was written to the value it references.
The variable i is written to until it reaches 10. None of the lambdas run until the loop completes so they all see the final value of i which is 10
I find this example is a bit clearer if you rewrite it as follows
int i = 0; // Single i for every iteration of the loop
while (i < 10) {
int x = i; // New x for every iteration of the loop
DoAction(() => {
Console.WriteLine(i);
Console.WriteLine(x);
});
i++;
};
DoAction spawns the thread, and returns right away. By the time the thread awakens from its random sleep, the loop will be finished, and the value of i will have advanced all the way to 10. The value of x, on the other hand, is captured and frozen before the call, so you will get all values from 0 to 9 in a random order, depending on how long each thread gets to sleep based on your random number generator.
I think you'll get the same result with java or any Object oriented Language (not sure but here it seems logical).
The scope of i is for the whole loop and the scope of x is for each occurrence.
Resharper helps you top spot this kind of problem.