When do you use the 'for' statement?

From ggc

Jump to: navigation, search

You typically use the for statement when you know how many times you want to do something. The most common example is when you want to do something with every element of an array. Since you know how long the array is (the array's name dot length, e.g. nums.length), you are going to do something a predetermined number of times (specifically once per array element. Here's some code that puts the number 2 into the entire array:

int[] nums=new int[5];
for(int x=0; x<nums.length; x++)
{
   nums[x]=2;
}

Does this start to answer your question?





Views
Personal tools
Add to 
del.icio.usAdd to 
diggAdd to 
FacebookAdd to 
favoritesAdd to 
GoogleAdd to 
MySpaceAdd to 
PrintAdd to 
SlashdotAdd to 
StumbleUponAdd to 
Twitter