We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13
For Loop
By Upekha Vandebona For
What it means in plain English: “Repeat 100 times.”
How the compiler sees it: ▪ create a variable i and set it to 0. ▪ repeat while i is less than 100. ▪ at the end of each loop iteration, add 1 to i. Part One: initialization Use this part to declare and initialize a variable to use within the loop body. You’ll most often use this variable as a counter. You can actually initialize more than one variable here, but it’s much more common to use a single variable. Part Two: boolean test This is where the conditional test goes. Whatever’s in there, it must resolve to a boolean value (true or false). You can have a test, like (x >= 4), or you can even invoke a method that returns a boolean. Part Three: iteration expression In this part, put one or more things you want to happen with each trip through the loop. Keep in mind that this stuff happens at the end of each loop. for(int i=0; i<8; i++){ Declare int i Set i to 0 System.out.println(i); } System.out.println(“done” ); true Is i < 8? Enter loop body (boolea n test)
Print the value fals
of i e Print “done” Increment i While Vs For
A while loop has only the
boolean test; it doesn’t have a built-in initialization or iteration expression.
Choose for loops over while loops when you
know how many times you want to repeat the loop code. Pre and Post Increment/Decrement Operator (++ and --) The Enhanced for loop
What it means in plain English: “For each element in nameArray,
assign the element to the ‘name’ variable, and run the body of the loop.” Part 1: Iteration Variable Declaration Use this part to declare and initialize a variable to use within the loop body. With each iteration of the loop, this variable will hold a different element from the collection. The type of this variable must be compatible with the elements in the array! For example, you can’t declare an int iteration variable to use with a String[] array. Part Two: the actual collection This must be a reference to an array or other collection. The Enhanced for loop
How the compiler sees it:
• Create a String variable called name and set it to null. • Assign the first value in nameArray to name. • Run the body of the loop (the code block bounded by curly braces). • Assign the next value in nameArray to name. • Repeat while there are still elements in the array. Thank You!