c# foreach looping even number - c#

I have the following foreach loop in C#:
foreach(var item in mod)
{
int i;
i = i + 1;
if (i % 2 == 0)
{
string y = "even number";
}
}
How come I get the message that local variable is unassigned. I am trying to find the even number here.

To resolve the message you are getting, you simply need to initialize it:
int i = 0;
If your intention is to count every item, then you will also need to change the scope of i to outside of the foreach. Otherwise, as you originally posted, the variable i will have the same value for every iteration of the loop.
See this code snippet for both the initialization and scope change:
int i = 0;
foreach (var item in mod)
{
i = i + 1; // is the first item considered even or odd? that answer changes where this should go
if (i % 2 == 0) {
string y = "even number";
}
}

You need to initialise your i variable:
int i = 0;
You're currently trying + 1 to an unassigned variable.

You get the warning because you are not assigning i before using it in i = i + 1. You want to declare i outside of your foreach loop, so you it isn't bound to the scope of the loop. Then initialize with 0 and use the increment feature. Something like:
int i = 0;
foreach (var item in mod)
{
i++;
if (i % 2 == 0)
{
string y = "even number";
}
}

An alternative to what others have suggested here (although correct) would be to use a for loop, this would take care of i for you, e.g.
for (int i = 0; i < mod.length; i++)
{
if (i % 2 == 0)
{
string y = "even number";
}
}

Change this: int i;
to this: int i = 0;
Values types in C# like int do have default values, but you're still not allowed to use an unassigned value-type variable.

You need to assign an initial value for i before you can do i=i+1

You have to initialize i. Right now the compiler is reading this as i = garbage in memory. So you have garbage in memory = garbage in memory + 1. That i could be equal to a string, a number, or anything.
int i = 0;
In addition, you need to initialize that variable outside of the for...each loop, or it will keep resetting itself to 0.
int i = 0;
foreach(var item in mod){
i = i + 1;
if (i % 2 == 0) {
string y = "even number";
}
}

int i = 0;
foreach(var item in mod)
{
if (i % 2 == 0)
{
string y = "even number";
}
i = i + 1;
}
//what are you doing with y and how are you returning y if you need it..
are you expecting to break out at some point.. ? what if item has zero items..??

Related

Scope of variables error

I'm pretty much new to C# programming.
I found this weird scope error in my program, my program won't run. It said below (at lbl[tx].BackColor = Color.DarkViolet;) that "Used of unassigned local variable". But I already declared variable tx inside in my method.
How to fix this? Any help is pretty much appreciated.
async void ShellSort()
{
int n = num.Length;
int gap = n / 2;
int temp;
int tx; /// Already declared tx here
while (gap > 0)
{
for (int i = 0; i + gap < n; i++)
{
int j = i + gap;
temp = int.Parse(lbl[j].Text);
while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
{
lbl[j-gap].BackColor = Color.Blue;
lbl[j].BackColor = Color.Blue;
await Task.Delay(time1);
lbl[j].Text = lbl[j - gap].Text;
tx = j;
j = j - gap;
}
lbl[j].Text = temp.ToString();
lbl[j].BackColor = Color.DarkViolet;
lbl[tx].BackColor = Color.DarkViolet; /// When I used
/// it here it wont work.
}
gap = gap / 2;
}
}
You declare the variable, but don't assign anything to it:
int tx;
You might assign to it in your loop:
while (j - gap >= 0 && temp < int.Parse(lbl[j - gap].Text))
{
//...
tx = j;
//...
}
// use tx here
But, what happens if that loop condition starts out as false? If the loop is never entered, no value is ever assigned. The compiler can't risk that. Though you might assign it a value, the compiler needs to ensure that you do assign it a value.
You can do this by simply assigning it a default value:
int tx = 0;
Integers default to 0 anyway when it comes to properties and whatnot. So one may as well do the same with local variables.
If body of your while will be never executed, tx will be unassigned. Compiler just tells you that you need initial value for this case.
So instead of
int tx;
write
int tx = 0; // or what is the correct value for you

c# How to put value outside of for looping?

I am starting to learn C#. I want to know how to put a value outside of a for loop like this:
int firstByte;
if (bytes == 1)
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
bytes is the length of comBuffer, and comBuffer's value is [0x01,0x06]. Is that a way to put the if(firstbyte == 0x06) outside of the for loop?. I want to put it outside of the for loop because I want add another if-else using if(firstbyte) outside of the loop.
My expectation is some like this:
int firstByte;
if (bytes == 1)
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
if(firstByte == 0x06)
{
string status = "OK";
}
When i try it, the program shows a warning message "unasigned value .....".
Any solution or suggestion?
Let's first understand what the problem is.
int firstByte;
**if (bytes == 1)**
{
for (int j = 0; j < bytes; j++)
{
firstByte = comBuffer[j];
if (firstByte == 0x06)
{
checkStatus = 2;
}
}
}
if(firstByte == 0x06)
{
string status = "OK";
}
firstByte is assigned a value only if bytes is 1, so there is this possibility of firstByte not being assigned anything and being checked in the outside if condition. You can easily avoid this problem by assigning firstByte a value like 0 or something that doesnt interfere with your logic.
int firtByte = 0;
will solve your problems.
assign default value at the time of declaration
int firstByte = 0;
int firstByte;
Your firstByte must have some value when assigning it.
for example:
int firstByte = 1;
Oherwise it cant be used with if because it has not the value to compare in statement.
When you declare a variable in your code without initializing it with a value, the compiler will throw an error if you try to access that variable unless your code guarantees that it will be assigned a value before it is accessed. In your example, you declare int firstByte; without assigning it a value. It doesn't receive a value until firstByte = comBuffer[j];, which is inside an if-block and a for-loop, either of which could conceivably skip the execution of their bodies without reaching that line of code.
Initializing firstByte with a value (such as int firstValue = -1;) will solve your issue.
Yes it is possible in two ways,
Make int firstByte as global
Assign a default value for firstByte.
Something like the following:
int firstByte=0;
Or
int firstByte=0X64;
Or some other values as per your requirements.
Why compiler is showing such message : Their may be chances for the condition bytes==1 evaluates to false, or the looping skip the loop. in such cases there is no assigned value for firstByte when you try to check it outside those conditions. Hence it shows the warning to make it perfect
I usually use nullables in this case:
int? firstByte = null;

Use of unassigned local variable please [duplicate]

This question already has answers here:
What does "Use of unassigned local variable" mean? [duplicate]
(11 answers)
Closed 6 years ago.
I created much for loops and want to put
value from a int to a string.
String strasze = dataGridView1.Rows[rows].Cells[straszeint].Value.ToString();
String stadt = dataGridView1.Rows[rows].Cells[stadtint].Value.ToString();
land = dataGridView1.Rows[rows].Cells[landint].Value.ToString();
hersteller = dataGridView1.Rows[rows].Cells[colIndex].Value.ToString();
kundennummer = dataGridView1.Rows[rows].Cells[kundennummerint].Value.ToString();
haendler = dataGridView1.Rows[rows].Cells[haendlerint].Value.ToString();
Here is a example for loop:
int landint;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(landname))
{
landint = i;
break;
}
}
What is wrong? It shows me the error on
straszeint,
stadtint,
landint
//EDIT
int straszeint;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(straszennamen))
{
straszeint = i;
break;
}
}
From your code, it is possible straszeint is never assigned a value. Assume what happens if datagridview.Columns.Count is 0, or there is no column matching the name. Then straszeint is never set to a value.
The compiler doesn't know what you know, so it just checks all paths and sees if there is a possible problem with an unset variable.
The easiest thing to do here is to set the variable to some arbitrary number and check that later:
int straszeint = -1;
for (int i = 0; i < datagridview.Columns.Count; i++)
...
if (straszeint == -1)
{
throw new Exception("Column 'straszennamen' could not be found!");
}
This is because Compiler is smarter than a developer
You should Initialize the local variables before accessing their values, In your case there may be changes for skipping the iteration of the loop, or the condition inside the loop will evaluate to false in all iteration. and you are using the value (say straszeint) after the iterations.
Compiler expecting such situations that's why it showing such errors.
You can simply solve this by initializing the variable either with 0 or any other value that's up to you.
int straszeint=-1;
for (int i = 0; i < datagridview.Columns.Count; i++)
{
if (datagridview.Columns[i].Name.Equals(straszennamen))
{
// Let it is false for all iterations
straszeint = i;
break;
}
}
// straszeint will be -1 here if the condition is false for all iteration
if(straszeint!=-1)
{
//Proceed with the action
}
Updates : Why should we initialize with -1 instead for 0
The .Cells will follows the 0 based indexing, So it will give the First cell value even if the condition evaluates to false.

Visual Studio c# Array Loop

I'm not sure if this has been asked before but I couldn't see it anywhere.
Can you loop an array? For example:
string[] = array1;
int num1 = 1;
do
{
lbl1.Text = array1[0]
}while(num1 = 1);
How can I make it so it adds one to the element every loop.
I agree that you need to better explain what you're trying to accomplish. If you hardcode num1 then perform a while num1 is equal to its initial value without ever modifying it, you're going to have an indefinite loop. In your example, it will just keep overwriting lbl1 to display the first item in your array.
By "add one to the element every loop", do you mean add each item in the array to your label? Try something like...
foreach (string item in array1)
{
lbl1.Text += array1[item];
}
Otherwise, please provide further details on what you're looking for.
It is really not clear what You want to achieve, but maybe this will get You nearer to the goal:
int[] array1 = new [] {0};
int num1 = 1;
do {
lbl1.Text = (array1[0]++).ToString();
num1++;
} while (num1 < 9);
or
int[] array1 = new [] {0};
for (int i = 0; i < 9; i++) {
lbl1.Text = (array1[0]++).ToString();
}
Not sure what you are trying to accomplish but the following is a stab at a solution
private static void foo(string[] array1)
{
if (array1 != null && array1.Length > 0)
{
for (int num1 = 0; num1 < array1.Length; num1++)
{
string doSomethingWithArrayElement = array1[num1];
}
}
}

How can i check the index length in long[] array?

For example i have a long[] x
And im doing:
for (int i=0; i<x.length;x--)
{
}
I know that in x for example i have 30 indexs cells.
How can i loop over the cells(indexs) in the x array and find on each cell the length of it and also to get/show the numbers in each cell.
If in x[0] there is 232
And in x[1] there is 21
And so on...
I want to display 232,21,....etc
And then i want to check that if x[i].length is above 0 do...
But there is no x[i].length
So how do i do it ?
I did:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
And its working but each time its showing me the number twice why the messagebox is working twice each time ?
If in the first array the number is 33454 then i see the messagebox once and then once again. Whats wrong here ? I want it to show me the number only once each time.
Its like repeating each number and show it once and then once again and only then moving to the next one.
EDIT **
Maybe the problem its showing the number twice each time have something to do with the scroll event im using ?
void trackBar1_Scroll(object sender, EventArgs e)
{
myTrackPanelss1.trackBar1.Minimum = 0;
myTrackPanelss1.trackBar1.Maximum = counter - 1;//list_of_histograms.Count-1;
long[] tt = list_of_histograms[myTrackPanelss1.trackBar1.Value];
histogramControl1.DrawHistogram(tt);
long res = GetTopLumAmount(tt, 1000);
long max = GetHistogramMaximum(tt);
if (res > -1)
label24.Text = (res / 1000.0).ToString();
setpicture(myTrackPanelss1.trackBar1.Value);
this.pictureBox1.Refresh();
}
For some reason its getting to the scroll and do everything here again. Twice in a row.
What can be the problem ?
A long[] basically holds a number of long values. Doing x[i].length is invalid, because a long does not have a property length. What is it that you are trying to achieve?
long[] x = {1,2,3} ;
x.length; //this is valid because you are querying the length / count of the array
x[0].length; //this is invalid because 1 does not have a property length
EDIT
Your loop counter will be the index. So,
for (int i =0; i < x.Length; i++)
{
//check for maximum, when you find it
Console.WriteLine("The maximum value is " + x[i]);
Console.WriteLine("The maximum value is present at index " + i);
}
As Michael says, you can find the length of the array via x.Length. In C#, x.Length (where x is an array) will return a 32-bit integer that represents the total number of elements across all dimensions. You only have a 1D array here, so that should be sufficient for what you're trying to achieve.
If you're also after the value stored in the array, the value is called as:
x[i];
So, in an example:
for ( int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
... would display the value in the array in your console.
Is that what you were asking?
Here is how to do something based on the values in the array.:
for (int i=0; i < x.Length; i++)
{
// print the number to the screen.
Console.WriteLine(x[i]);
if (x[i] > 0) {
// do something else.
}
}
I'm not sure what you meant by x--, but that's probably wrong from your description.
You could cast it to a string and get the length property.
x[i].ToString().Length
Although if you want to check if the length is above zero, then surely just the presence of a value proves this?
Your function has a terrible problem:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
long count = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > 0)
{
MessageBox.Show(histogram[i].ToString());
break;
}
}
return result;
}
This way, you check the values in your array.
When i=0, it checks x[i]. So, 33454 (the value you gave in x[0]) is greater than 0, it shows the number and "break;", so it stops the "for" and do what's next: it returns the result variable that is never modified.
So variables result and count are useless in your code.
Rewrite with something that way for getting the maximum in your array:
public long GetHistogramMaximum(long[] histogram)
{
long result = 0;
for (int i = 0; i < histogram.Length; i++)
{
if (histogram[i] > result)
{
MessageBox.Show(string.Format("{0} is greater than {1}", histogram[i], result);
result = histogram[i];
}
}
return result;
}

Categories