confusing "for loop" in c#, when exit the values get cleared - c#

I am just new to c#, please help me understanding for loop in c#..
Issue: I am trying to use j further into my code but after exit out from for loop , it shows j is not exist in the current content.
Is this correct behavior in C# ? how do I get to use j outside the loop?
for (int i = 0; i < 4; i++)
{
int j;
j = 10;
//print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
//print j outside the loop, which throws error
System.Windows.Forms.MessageBox.Show(j.ToString());

You need to get better acquainted with variable scopes in C# - there is a lot of documentation around if you google it.
As for your code, if you want to access the variable outside the for loop, you need to declare it outside the for loop, e.g.
int j = 0;
for (int i = 0; i < 4; i++)
{
j = 10;
System.Windows.Forms.MessageBox.Show(j.ToString());
}
System.Windows.Forms.MessageBox.Show(j.ToString());

In Your code You declare the variable j inside the loop that's why You cannot able to access the variable.
So declare the variable outside the for loop
just like below,
int j=0; // Declare here
for (int i = 0; i < 4; i++)
{
j = 10;
'print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
'print j outside the loop, which throws error
System.Windows.Forms.MessageBox.Show(j.ToString());

That's not how C# works.
Your variable j is defined within the scope of the loop. That means it is not accessible from outside the loop.
See the documentation here.
If you want to be able to access the variable from outside the loop, you must declare it from outside the loop as well.
int j;
for (int i = 0; i < 4; i++)
{
j = 10;
}

You cant. its out of scope as you've defined it.
Imagine im the for loop, you gave me the job of doing it.. I think J=10 and make note of it a few times.. i then tell you i did the job.
you then try to use a thing I though of ..
You need to adjust the code.
int j=0;
for (int i = 0; i < 4; i++)
{
j = 10;
'print j within the loop, which works fine
System.Windows.Forms.MessageBox.Show(j.ToString());
}
System.Windows.Forms.MessageBox.Show(j.ToString());
now j exists, inside the loop because it already is made.. so I come and find a postit called "j" and I can write 10 on it. You come back after Im done, the postit is still there.

Related

I created a for loop and it doesnt work, but the while loop does, any sugestions?

Why doesnt this for loop work while the while loop does
for (int i = 0; i > 10; i++)
{
Console.WriteLine(i);
}
int j = 1;
while(j != 11)
{
Console.WriteLine(j);
j++;
}
It's easy to mix up comparers. A good way to remember for me is the heart. <3 because I know that's read as "Less than three".
It's easy to get confused when starting out, you just mixed up the condition.
As of why your for does not work is because it starts with i = 0 then checks if if 0 is greater than 10 which is not that's why it will not excute the loop body and terminates the loop.
In your while loop, initially j = 1 then while checks if 1 is not equal to 11, which is true so loop body will execute until j is not equal to 11.

How does a for loop allow redeclaration of a variable?

This:
int j = 1;
int j = 2;
Console.WriteLine(j.ToString());
.. produces a compile error:
A local variable named 'j' is already defined in this scope
Yet this works fine:
for (int i = 0; i < 10; i++)
{
int j = i;
Console.WriteLine(j.ToString());
}
Why?
How does the loop simultaneous retain values from each iteration whilst being able to redeclare a variable with the same name in the same scope?
The variable j exists only per iteration, i.e. in each iteration a variable j is declared, assigned, used and then discarded and the next iteration begins and the process repeats and so forth. hence you don't get the same compilation error as the first example snippet.
When you write int j=1 and int j=2, you are trying to declare the variable twice (you can only declare it once).
You could, however, overwrite the value of j:
int j = 1; // now j has a value of 1
j = 2; // now j has a value of 2
This is what the for loop is doing - each iteration of the for loop, the value is updated. A new instance of j is not created during each iteration.
In the first example you are defining two variables with the same name, and they exist at the same time.
In the loop, every variable is created in the loop context. After each iteration the variable is destroyed, allowing you to create a new one with the same name(on the next iteration). In other words, on the loop they don't exist at the same time.

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.

Step n before an operation in a C# for loop

A standard "for" loop I use is something like that:
for (int i = 0; i < x; i++)
which increments i by 1 every time after it passes thru a loop.
I was wondering if there is anything like a VB's Step n operation in C#'s "for" loop. I googled and found out the only thing I can possibly do is (assume n=2)
for (int i = 0; i < x; i += 2)
That's fair enough. But that brings me to the next question. What if I want to change a loop that increments i BEFORE it goes into it, like:
for (int i = 0; i < x; ++i)
Is there any elegant way to do it, or do I need to go into first loop already with i incremented and increment it at the end of each loop OR before beginning all loops after the first one OR do other crazy stuff?
i += 2
for (int i = 0; i < x; i++)
{ i++; }
or
i += 2
for (int i = 0; i < x; i += 2)
or
for (int i = 0 - 2; i < x - 2; i += 2)
I assume incrementing before a loop might not be possible in all cases, hence i thought there should be some other way to do it.
I was wondering if there is anything like a VB's Step n
You have the right C# equivalent:
for (int i = 0; i < x; i += 2)
What if I want to change a loop that increments i BEFORE it goes into it
I may be missing something, but it sounds like you just want to change your starting value:
for (int i = 1; i < x; i++)
Also note that:
using ++i or i++ makes no real difference here, since you're not doing anything with the return value within the for statement, which is the only difference between using ++i and i++
you can't do the following:
i += 2;
for (int i = 0; i < x; i += 2)
because you can't re-declare i as part of the for loop if it;'s already declared outside of the loop.
EDIT
The for loop for (initializer; condition; iterator) is functionally equivalent to:
{
initializer;
while(condition)
{
.. do something
iterator;
}
}
It sounds like you want some sort of for loop that is equivalent to:
{
initializer;
while(condition)
{
iterator;
.. do something
}
}
there is no such single-statement construct in C#. If you want that series of events you'll have to use a while loop like the above or change the statements in your for loop to provide equivalent functionality.
Just initialize i to 2 to start at 2 rather than trying to execute the looping statement before the body.

Getting all the possible distances between points

I have created a program to spawn a number of points (the number is given by the user).
Therefore the program spawns N points
see the image for an example, it has 3 points in that case
What I need is to get all the possible distances between those villages (In the example it's distance: AB, AC, BC).
The points are stored in a single array (that scores x-coordinate and y-coordinate)
List<Villages>
I know that I new Pythagoras Theorem, I just cannot get the foreach loop right.
I would think you would want a regular nested for-loop rather than foreach.
Something like this should work:
for (int i = 0; i < villageList.Count; ++i)
{
for (int j = i + 1; j < villageList.Count; ++j)
{
distanceFunc(villageList[i], villagelist[j]);
}
}
Where distanceFunc is whatever implementation of a distance function you want to use and villageList is your List of villages.
The reason you would use for-loops is because you need the inner loop to start one element past the the outer loop (i + 1), and foreach loops don't let you easily access the index you're currently at (they let you access the element itself, but not easily see it's position in the array).
You need two for loops:
var villages = new List<Villages>() { ... };
for (int i = 0; i < villages.Count - 1; i++)
for (int j = i + 1; j < villages.Count; j++)
Console.WriteLine(getDistance(villages[i], villages[j]));
Where getDistance you should write yourself. It should return a distance between two specified Villages.
How about something like this pseudocode:
villages = [a, b, c, ...]
for i=0 to len(villages)-2:
for j=i+1 to len(villages)-1:
print(villages[i], villages[j], dist(villages[i], villages[j]))

Categories

Resources