Presentation is loading. Please wait.

Presentation is loading. Please wait.

While Loops BIS1523 – Lecture 12.

Similar presentations


Presentation on theme: "While Loops BIS1523 – Lecture 12."— Presentation transcript:

1 While Loops BIS1523 – Lecture 12

2 While loops While for loops are typically used to do something a set number of times, the while loop executes code any number of times, based on a condition. The for loop checks the condition, if it is true, executes all of the code inside the {}’s, then repeats the process. Like the for loop, care needs to be taken so that the condition can be satisfied, so your code inside the loop has to result in the condition becoming false, at some point.

3 Example While You can use a while loop to do similar things that a for loop would do: Rather than being included in the syntax for the while, the initialization, and incrementing has to be handled separately. This would be the same result as the for loop: for ($x=1; $x <= 5; $x++) { print “The number is $x <br />”; }

4 Example Loop Consider the following problem:
You have some amount of money in your account, and it generates 6% interest per year. How long does it take for you to have 1 million dollars? This problem is not easily solved with a for loop, as you don’t know how many times to run the loop. To solve the problem, we need to run a simulation, and have the account start out at the amount, and each time grow it by the appropriate amount. Each time we do this, we have a $count that goes up by 1. After the loop, the value of $count will be ‘how many years’.

5 Example While The ending condition is “when balance is bigger than a million”, so we want to keep adding to the balance as long as it is less than a million. Each time we add the interest earned to the balance, and count it. After the loop print out $count. Why would this loop not work if you used the condition: while ($balance != )

6 Simulation Example Consider the following problem:
Assume each time through the loop the gambler has a 50% chance to win. We can use a random number to determine win/loss at each loop. What would be the condition for the loop?

7 Simulation Example So, we want to do the loop as long as $stake is not 0, and is also not $goal. Each time through the loop, generate a random number (we’ll use 1-100), and if it is less than half, we lose 1, if its greater, we win 1. We start with 100 And want to get to 200

8 Nesting Loops In the previous example, because we were dealing with random numbers, we got a different outcome each time we ran the simulation. If we wanted to figure out how often we won, and how often we lost, we would need to do that simulation many times. We could put that entire loop inside a for loop, and run it 1000 times, counting how many times we won, and lost, and print out the results. This is a common method for running computer ‘simulations’.

9 Simulation Example The red & purple lines below were added to show what code sections were in each loop We took the entire while loop, as well as the starting values for variables and put them inside a for loop. The final result is printed out after both loops have run. When one loop is inside another, they have a multiplying effect on how many times code is run.

10 Post Test Loops You can also do a while loop where the condition is checked at the end of the loop This ensures that the loop is executed at least once. After the very first iteration of the loop, this works no different than the pre-test version. Pre-test loops are executed 0 or more times. Post-test are executed 1 or more times.

11 Nested For Loops We could use 2 nested for loops to create a table in HTML. Consider how how you describe a table in HTML <table> <tr> [All the <td> for each column in row 1] </tr> Etc You are looping through every row, and inside each row looping through every column.

12 Tables with fors The outer most for loop is for each row, the inner one is for each column. Notice that in this case, 15 cells are printed, 3 rows of 5 columns. When you nest for loops, the number of times the inner set of code is executed is I x J….they have a multiplying effect.

13 Arrays Arrays constitute a complicated but very useful notion. Whereas numbers and strings can only store a single value, arrays can contain many values. An array can consist of numbers and/or strings (and/or other arrays), which allows this one variable to hold exponentially more information than a simple string or number can. For example, if you wanted to create a grocery list using strings, your code would look something like this: For each added item, you’d need to create a new string. This approach is cumbersome, and it makes it difficult to refer back to the entire list or any specific value later in your code.

14 Arrays An array, on the other hand, acts like a list, where each item on the list is referred to by a row number. The list would have a single variable name like $items To refer to an individual row, you could access $items[1], or $items[2], etc…

15 Creating Arrays The formal method of creating an array is to use the array() function. Arrays automatically begin their indexing at 0, unless otherwise specified. In that example—which doesn’t specify an index for the elements—the first item, apples, is automatically indexed at 0, the second item at 1, and the third at 2. The array $list would then have the values: You could refer to $list[0], $list[1], etc. Apples 1 Bananas 2 Oranges

16 Creating With Specific Indices
You can assign specific indices when you create an array: Because PHP is very liberal when it comes to blank space in your scripts, you can make this structure easier to read by writing it over multiple lines: 1 Apples 2 Bananas 3 Oranges

17 Strings as indices The index value you specify doesn’t have to be a number—you can use strings as well. This indexing technique is practical for making more meaningful lists. As an example, you could create an array that records the soup of the day for each day of the week, as in the following script. You could then access different rows of the array like: $soups[‘Monday’] $soups[‘Tuesday’]

18 Adding Elements to an Array
You can add an element to an array (or change an existing element) by using an assignment statement. The assignment statement replaces a value if one exists on that row, or adds a new value if one did not exist. If you don’t specify the row number, it just adds the elements to the next logical row values. You can specify which row you want the values on as well For arrays with strings as row names, you’ll always want to specify the row names.

19 Removing Elements To add something to the soup array:
To remove an element from an array, use the unset function To delete all the elements from an array, use the array function again

20 Accessing elements You can access an element of an array just like any other variable, specify its name and row number If the array uses strings for indexes, which should be quoted, you must adjust for the quotation marks you’d use around the index, because they conflict with the print syntax. Ironically, the feature that makes arrays so useful—being able to store multiple values in one variable—also gives it a limitation the other variable types don’t have: You must know the keys of the array in order to access its elements.

21 For each loops The fastest and easiest way to access all the values of an array is to use a foreach loop. This construct loops through every element of an array: With each iteration of the loop, the current array element’s key will be assigned to the $key variable and the value to $value.

22 For each example Given the soup array: This foreach loop:
The loop steps through the array, top to bottom. At the first iteration, $day becomes ‘Monday’, and $soup becomes ‘Clam Chowder’. The resulting output is:

23 Foreach If you only need to access an arrays values, and not it’s keys, you can leave off the “$key” field from the foreach loop Arrays with numeric indices (0, 1, 2, etc) are good examples of when you might not need to know what row a thing is on, only that the thing is in the array. It also works on string indexed arrays as well. With this array and loop, it would print out each soup in turn (but not the associated day).


Download ppt "While Loops BIS1523 – Lecture 12."

Similar presentations


Ads by Google