-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.

1
  • 6
    Have you learnt about arrays yet? Commented Feb 14, 2022 at 9:35

2 Answers 2

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++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I want to supply some additional information about your question, C# is strongly typed so you can't create variables dynamically.
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;

1 Comment

Good idea, last thing we need is an IndexOutOfRangeException.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.