This question already has answers here:
Create dynamic variable name
(5 answers)
Closed last year.
Ok this might be a weird question and I don't really know how to phrase it so I just show you an example:
int i = 0;
int k = 100;
while (i <5) {
***response+i*** = k + i;
i++;
}
I want to declare multiple Variables (response1, response2, respons3 ...) using a loop, so that in the end the result is:
response1 = 101
response2 = 102
response3 = 103
etc.
I am still a beginner at C# and programming in general, so I don't know if that is even possible how I imagine it, hope you can help me, thanks.
First, You can not define a variable by using two variable. That is not how compiler work.
Maybe you should try to create a Array or List to store the value
like this example
int i = 0;
int k = 100;
int[] response = new int[100];
while (i < 5)
{
response[i] = k + i;
i++
}
if you don't know the array size you want , try to do with List
List<int> response = new List<int>();
int i = 0;
int k = 100;
while (i < 5)
{
response.Add(i + k);
i++;
}
You should really use an array for these values, it's not really possible to use dynamic variable names.
I would also use a for loop where you need the index variable rather than having to manually update it in the while loop.
var results = int[5];
int k = 100;
for (var i = 0; i < results.Length; i++)
results[i] = k + i;
Related
Im new to programming i use c# to solve some problem but i have problem when user input two integer no in same-line and i want to look for zero and remove it from each no i think by replacing with the next array cell i should convert integer to string again but i cant do it please help me
string[] arr = Console.ReadLine().Split(' ');
string a = arr[0];
string b = arr[1];
int[] m = new int[1];
int[] n = new int[1];
for (int i = 0; i < a.Length; i++)
{
if (a[i] == 0 && a[a.Length - 1] != 0)
{
for (int j = i; j < a.Length; j++)
{
//****m[i] = int.Parse(a[i]); the error here cant convert from char to string ??
// a[i] = a[i + 1];**\\ Error CS0200 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only**
I don't really know what you're trying to do, but if you're trying to convert the char into an ASCII value, then you would have to use the static method of Char called GetNumericValue.
Information on GetNumericValue can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.char.getnumericvalue?view=netcore-3.1
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 4 years ago.
I'm writing a Assignment for school (we are sepose to make one for the rest of the class) and I have run in to a problem. I'm having IndexOutOfRangeException errors when running the program and I can't figure out why I'm getting it.
Random rnd = new Random();
string strNumDice = tbxNumDice.Text;
int[] numDice = new int[int.Parse(strNumDice)];
int numSides = int.Parse(tbxNumSides.Text);
int trgNumber = int.Parse(tbxTarget.Text);
int sum = 0;
//int numTries = 0;
int var2 = 0;
if (int.Parse(strNumDice) * (numSides) >= trgNumber)
{
while (var2 != trgNumber)
{
tbxResult.AppendText("\n");
sum = 0;
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
tbxResult.AppendText(numDice[numberOfDice].ToString() + " ");
sum += numDice[numberOfDice];
//numTries++;
}
tbxResult.AppendText("\n");
tbxResult.AppendText("The new sum is" + sum.ToString());
var2 = sum;
}
}
If I decide to roll 6 d6's and wan't a target sum of 36 it will continue to do so until it gets to 36.
The mistake is here:
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
This is how javascript does foreach loops: you get the indexes of your array. C# gives you the values of the actual elements, rather than the indexes. As you will be modifying actual array elements, you want a for loop, rather than a foreach loop, like this:
for(int i = 0; i<numDice.Length; i++)
{
numDice[i] = rnd.Next(1, numSides+1);
This question already has answers here:
List items changes as I add new data... why?
(6 answers)
Closed 6 years ago.
I need to create a dynamically sized list that contains pairs of points for a window's form using C#. The list size will change depending on the data that is loaded.
A simplified version of my approach, to simply convey the problem, is as follows (in the real app, the for-loops will iterate over sizes dependent on loaded data):
int[,] dummyInt = new int[1, 2];
List<int[,]> test = new List<int[,]>();
for (int i = 0; i < 100; i++)
{
dummyInt[0, 0] = i;
for (int j = 0; j < 5; j++)
{
dummyInt[0, 1] = j;
test.Add(dummyInt);
}
}
//Show the values in the list for debugging
foreach (int[,] value in test)
{
MessageBox.Show(value.ToString("G"));
}
Using this approach, all 500 values in the list are [99,4].
What I was expecting/hoping to get was
value 1 [0,0]
value 2 [0,1]
...
value 500 [99,4]
Seems like the list is storing the actual variable, and then changing the value with every iteration of the for loop. How can I store just the value of dummyInt as a new object to the list?
I searched for this, but I'm not sure I know the appropriate vocabulary to nail down the search.
Your List object is storing reference to the dummyInt object. If you want to store different values in List you have to create new int array every time you are adding it to List.
Reference:
https://msdn.microsoft.com/en-gb/library/4d43ts61(v=vs.90).aspx
Firstly, you don't need a 2-dimensional array if you're just storing a pair of coordinates. The first coordinate can go in the first element of a 1-dimensional array, and the second coordinate can go in the second element of the array. Secondly, the Clone method can be used to make a copy of an array object if you want to force a separate copy of the whole array to exist.
int[] dummyInt = new int[2];
List<int[]> test = new List<int[]>();
for (int i = 0; i < 100; i++)
{
dummyInt[0] = i;
for (int j = 0; j < 5; j++)
{
dummyInt[1] = j;
test.Add((int[])dummyInt.Clone());
}
}
foreach (int[] value in test)
{
Console.WriteLine("({0},{1})", value[0], value[1]);
}
And finally, an array might not be the best way to store a pair of coordinates. You might want to use a tuple or make your own structure. If you use a Value type (struct) instead of a Reference type (class), you don't need to clone each one.
struct Pair
{
public int x;
public int y;
}
public class Test
{
public static void Main()
{
Pair dummyInt = new Pair();
List<Pair> test = new List<Pair>();
for (int i = 0; i < 100; i++)
{
dummyInt.x = i;
for (int j = 0; j < 5; j++)
{
dummyInt.y = j;
test.Add(dummyInt);
}
}
foreach (Pair value in test)
{
Console.WriteLine("({0},{1})", value.x, value.y);
}
}
}
Note how the result is different if you change the word struct at the beginning to class.
I feel like this task should not be done this way...
My sequenceY length is not equal to number of steam numbers because you can't assign int[] length with int that have 0 as a starting value.
Therefore my sequenceY have a lot of 0 inside and I can't print the whole sequence. I even tried adding this after for loop:
sequenceY = new int[steamnumbercounter];
But it didn't work ... Why ?
My other question is how do programmers deal with sequences that have unknown length?
I managed to print only steam numbers but the task says print sequenceY not only part of it.
// 4. sequenceX[20] is made of random numbers from 1 to 30 ,
// sequenceY is made of steam numbers from sequenceX. Print sequneceY.
int[] nizx = new int[20];
int[] nizy = new int[20];
int n = 0;
int steamnumbercounter = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i]%2==0)
{
nizy[n] = nizx[i];
n++;
steamnumbercounter++;
}
Console.Write("{0} , ", nizx[i]);
}
for (int i = 0; i < steamnumbercounter; i++)
{
Console.WriteLine("{0} , ",nizy[i]);
}
Partial code review along with an answer.
But it didn't work ... Why ?
That code didn't work because you're reassigning sequenceY to a completely new value.
My other question is how do programmers deal with sequences that have unknown length?
So, with that known we can do a few things here: create an array and use Array.Resize, use a List<T>, fill the initial array then swap it for one of the right size which is filled.
I'm going to assume a "steam" number is an even one.
Your naming is not good: nizx and nizy don't convey the meaning or line up with the problem.
I'm going to demonstrate the last option (since you stated that you don't know how to use many of the moderately complex parts of .NET in this class yet, which is fine): fill the initial array and swap it for a new one. This will run in O(n^2) time (sorta).
So, let's start with our source array.
int[] sequenceX = new int[20];
Next we'll define our destination array to be the same size as our source array. (This is the maximum number of values that could be stored in it, we'll shrink it later.)
int[] sequenceY = new int[sequenceX.Length];
Then we need a variable to hold how many numbers we found that meet our criteria:
int steamNumbers = 0;
And lastly, our Random.
Random random = new Random();
Then, we look through all our sequenceX as you did, but we'll update the logic a bit.
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
So our code looks almost the same as yours, but we have one more thing to do: since you only want sequenceY to contain steamNumbers we have to shrink it or something.
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
Now sequenceY only has your steam numbers in it.
Final code:
int[] sequenceX = new int[20];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(1, 30);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
// Print your `sequenceY` here.
You could extract this to a method pretty easily as well:
public int[] GetSteamNumbers(int sequenceCount, int randomMinimum, int randomMaximum)
{
int[] sequenceX = new int[sequenceCount];
int[] sequenceY = new int[sequenceX.Length];
int steamNumbers = 0;
Random random = new Random();
for (int i = 0; i < sequenceX.Length; i++)
{
sequenceX[i] = random.Next(randomMinimum, randomMaximum);
if (sequenceX[i] % 2 == 0)
{
sequenceY[steamNumbers] = sequenceX[i];
steamNumbers++;
}
}
int[] tempSequenceY = sequenceY;
sequenceY = new int[steamNumbers];
for (int i = 0; i < steamNumbers; i++)
{
sequenceY[i] = tempSequenceY[i];
}
return sequenceY;
}
And then call it with:
int[] steamNumbers = GetSteamNumbers(20, 1, 30);
Of course, for the more advanced users (this doesn't help you, but it may help others) we can do something as follows using LINQ:
var random = new Random();
var sequenceY = Enumerable.Range(1, 20)
.Select(x => random.Next(1, 30))
.Where(x => x % 2 == 0)
.ToArray();
Which should have the same effect. (Just demonstrating that there are still things in C# to look forward to in the future.)
Disclaimer: I wrote this entire answer outside of the IDE and without actually compiling it, I make no guarantees to the accuracy of the code but the procedure itself should be fairly straight forward.
The thing with arrays in C# is that they are of fixed size.
You'll have to iterate through and re-create it or use a IEnumerable that has dynamic sizes, such as Lists.
Solution here would be to use a List that contains your integers and then you would use nizx.Add(rnd.Next(1, 30));
Elaborating on my comment above: You can create a 'fake' list by concatenating the values you need in a string, separated by commas. The string.Split(',') will give you the resulting array that you need.
Given a string of form "a,b,c,d" string.Split(',') will create the array ["a","b,"c","d"]. The code:
{
int[] nizx = new int[20];
string numberString = string.Empty;
int n = 0;
Random rnd = new Random();
for (int i = 0; i < nizx.Length; i++)
{
nizx[i] = rnd.Next(1, 30);
if (nizx[i] % 2 == 0)
{
numberString += nizx[i] + ",";
n++;
}
}
var numberArray = numberString.Split(',');
for (int i = 0; i < n; i++)
{
Console.WriteLine("{0} , ", numberArray[i]);
}
}
I have an array of velocity and I want to get an array of displacement.
To get displacement for each n,i need add speed[] from 0 to n,
So I'm trying to add first n numbers for each n in array speed[],n is the index of array start from 0.
for (i = 0; i < totalnumber; i++)
{
for (int k = 0; k < i; k++)
{
Xdis[i] += Xvelo[k];
Ydis[i] += Yvelo[k];
Zdis[i] += Zvelo[k];
}
}
the loop above works,but the problem is it takes too long(loop in loop)
my question is, is there any sum function in C# can handle this without use for loop?
like Xdis[i]=Xvelo.sum(i) or sth?
Why don't you use the results you already calculated? Instead of re-summing all the way up, just use the previous result:
for (i = 1; i < totalnumber; i++)
{
Xdis[i] = XDis[i-1] + Xvelo[i-1];
Ydis[i] = YDis[i-1] + Yvelo[i-1];
Zdis[i] = ZDis[i-1] + Zvelo[i-1];
}