Question:
Jgrasp: How to declare a variable inside a loop?
Nickname?
2012-12-29 21:53:45 UTC
I am having difficulties declaring a variable inside a loop... would it be possible for somebody to kindly post the basic structure of it? I want multiple variables to be created at the end of the loop, but the number of variables to be created is to be determined by the user.

This is what I have so far, which is terribly wrong.

for (int i = 1; i <= 5; i ++) // the '5' value could vary based on a predeclared variable
{
int valuei=0;// I want 5 variables that go value1, value2, value 3 and so on, to be declared at the end of this loop
}

Thank you so much!!!
Four answers:
Daniel
2012-12-29 21:55:04 UTC
Value 4-(1i++)7-4 to the power of 5/3 duh
DUDEperson
2012-12-29 22:04:44 UTC
You don't want to declare a variable inside a loop.

You would want to create an array of integers that has a length of 5.



The following line creates a new spot for an array

int[] arrayNameHere;



This line creates an array of integers of length 5 and puts it into the array called "arrayNameHere".

arrayNameHere = new int[5];



Alternatively, you can do the following to keep it in one statement:

int[] arrayNameHere = new int[5];



The for loop would look like this:

for (int i = 0; i < 5; i++)

{

arrayNameHere[i] = 0;

}



This for loop will go through 5 times. Keep in mind that arrays start counting at 0, so the length is 5 and so is the number of objects. However, the counting goes from 0 to 4. The for loop starts at 0 and ends at 4, THE ARRAY DOES NOT START AT 1 AND END AT 5.



It is also common to do the following if the number of objects changes during the program:

for (int i = 0; i < arrayNameHere.length; i++)

{

arrayNameHere[i] = 0;

}



If you want the user to assign the length or number of variables, let the user define the value of the integer x.

arrayNameHere = new int[x];
Joshua
2012-12-30 08:44:29 UTC
Firstly, remember that all the variables you declare inside a loop ceases to exist after the loops life time. it is better you make use of an array pre - declared and then initialize the values in the loop. but you must have specified the size outside the loop.





int values[] // creates an array of unknown size

int x = user number of variables

values = new values[x]

for (int i = 0; i < x; i++){



values[i] = 0;

}



this should give an array of size, the user number of variables.
gentner
2016-10-22 09:51:12 UTC
Defining the iterator as component to the for loop could artwork high quality. do not attempt this with the different variable, regardless of the reality that. And this is no longer extremely a ideal way of doing this - that's effortless to ignore which variables you've used earlier, and also you should get some thing unpredictable out of it.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...