Wednesday, October 21, 2009

Hey could anyone out there explain loops in java to a very stressed student?

It's pretty simple. Let's say I have an array of 5 numbers, and I want to add 1 to each. If I use a loop, I can go from 0 to 4 (the indices of the array) and add 1 to each value in 2 lines of code, or I can write 5 lines of code to do what I want. That's a simple example. Now imagine my array has 100 members. Now imagine 1,000. Imagine 1,000 lines of code, for something that could be done in 2, which would you prefer?





simple:





for (int i = 0; i %26lt; 5; i++)


myArray[i] = myArray[i] + 1;





complex:





myArray[0] = myArray[0] + 1;


myArray[1] = myArray[1] + 1;


myArray[2] = myArray[2] + 1;


myArray[3] = myArray[3] + 1;


myArray[4] = myArray[4] + 1;





The idea of a loop is that the code within the body of the loop can execute more than once (if at all) given certain conditions. This allows us to write less code to perform more complex tasks, it gives us another way of solving a problem without having to copy and paste code and modify it (never copy and paste code within a project, if you have to do this, then you've made a mistake in your design and you need to refactor a function!).





A while loop executes while the condition is true:





while (condition)


{


// do stuff


}





A do-while loop executes at least once, and continues executing while the condition is true:





do


{


// do stuff


} while (condition);





A for loop executes an initial condition, a check condition, and a statement per iteration:





for (initial; condition; statement)


{


// do stuff


}





For loops are tricky for beginners, you can convert a for loop to a while loop like this:





initial;


while (condition)


{


// do stuff


statement;


}





I often use my last example to explain for loops, and start with while loops. My last example is a common test question, so memorize it!

Hey could anyone out there explain loops in java to a very stressed student?
This link:


http://mindprod.com/jgloss/forloop.html


You should be able to get what you need.



poems

No comments:

Post a Comment