-1

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
CTSB
  • 1

2 Answers2

1

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++;
}
TianRy1337
  • 19
  • 5
  • I want to supply some additional information about your question, C# is strongly typed so you can't create variables dynamically. – TianRy1337 Feb 14 '22 at 09:53
1

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;
phuzi
  • 12,078
  • 3
  • 26
  • 50