Code Challenge 3
Posted on 12. Mar, 2010 by admin in Basics
Me again! I hope you are having fun with loops and arrays, so let’s test your knowledge.
Questions
Q: What is a loop?
Show Answer ▼
A loop allows for the repeating of portions of code over and over again.
Q: What is the syntax when using a For loop?
Show Answer ▼
<?php
for ( counting var; conditional statement; increment var)
{
//code
}
?>
Q: What is the syntax for a While loop?
Show Answer ▼
<?php
while ( conditional statement)
{
//code
}
?>
Q: What is an infinite loop?
Show Answer ▼
The loop condition is never met and the loop keeps repeating forever.
Q: What is an array index?
Show Answer ▼
A location in an array with an individual value.
Programming Projects
Project One: Write a program that prints out “I Love WildPHP.com!” 10 times. Use While and For loops.
Show Answer ▼
<?php
//For Loop
for($i=1; $i<=5; $i++)
{
echo "I Love WildPHP.com! ";
}
//While Loop
$i=1;
while($i<=5)
{
echo "I Love WildPHP.com! ";
$i++;
}
?>
Project Two: Write a loop that will add all the numbers in the following integer array: 22, 56, 7, 32, and 11.
Show Answer ▼
<?php
//Declare Array
$numbers = array(22, 56, 7, 32, 11);
//Sum Variable
$sum = 0;
//For Loop
for($i=0; $i<5; $i++)
{
$sum += $numbers[$i];
}
echo "The sum is ".$sum;
?>
Output:
The sum is 128