Website Development Prices

Search Blog

Sunday, December 20, 2015

Petlja while (Loop while)

Drugi vazan tip petlji su while petlje. Umesto da se koristi indeks petlje, ponavlja se ova petlja sve dok je zadati uslov tacan.

while (izraz) iskaz

Iskaz moze biti i slozen iskaz, koji se postavlja u velike zagrade. Petlja se ponavlja sve dok je izraz tacan. Ako ne zelite da se petlja ponavlja do beskonacnosti, morate nesto da uradite da iskaz dovede do toga da u nekom trenutku izraz postane netacan.

Primer: ako zelite da prikazete vrednost promenljive sve dok je njena vrednost manja od 12.


$vrednost = 1;
while ($vrednost < 12) {
echo "Nova vrednost:", $vrednost, "<br>";
$vrednost *=2;


Sacuvajte ovaj fajl kao petlje-while.php.


Nova vrednost:1
Nova vrednost:2
Nova vrednost:4
Nova vrednost:8

Objasnjenje: vrednost svake promenljive smo povecali za dva puta. Pre pocetka petlje dodeli smo promenljivoj vrednost, tako da ne pocne od 0 (sto bi znacilo da bi petlja bila beskonacna). Ova petlja prkazuje trenutnu vrednost promenljive. U svakom prolazu se ta vrednost duplira, sve dok vrednost ne predje 12.

Another important type of loop is a while loop. Instead of using index loop, this loop repeats until the given condition is true.

while (expression) statement

The statement can be a complex statement, which is placed in the braces. The loop is repeated until the expression is true. If you do not want to loop repeat infinitely, you need something to do to cause the statement that at some point the expression becomes false.

Example: if you want to show the value of a variable as long as its value is less than 12.


$value = 1;
while ($value < 12) {
echo "Now new value is:", $value, "<br>";
$value *=2;


Save this file as while-loop.php.


Now new value is:1
Now new value is:2
Now new value is:4
Now new value is:8

Explanation: the value of each variable was increased by two. Before the beginning of the loop, we assign a variable value, so it doesn't start from 0 (which means that the loop would be infinite). This loop shows the current value of the variable. In each pass the limit is doubled, as long as the value does not exceed 12.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.