-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLooping_using_function.php
78 lines (56 loc) · 1.47 KB
/
Looping_using_function.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/*
* Write a PHP Function that uses a for loop to print all even Numbers form 1 to 20, but with a step 2 .
* In other words, you should print 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.
* The function should take arguments like start as 1, end as 20 and step as 2.
* You must call the function to print.
* And do the same using while loop and do-while loop aslo.
*/
//Using for loop:
function isEven($start, $end)
{
for ($i = $start; $i <= $end; $i++){
if($i % 2 == 0) {
echo $i . ' ';
}
}
}
isEven(1,20);
echo PHP_EOL;
////////////////////////////////////////////////////////////////
//Using While loop:
function isEven1($start, $end)
{
$i = $start;
while($i <= $end){
$i++;
if($i % 2 == 0) {
echo $i . " ";
}
}
}
echo isEven1(1, 20);
echo PHP_EOL;
////////////////////////////////////////////////////////////////
//Using Do-While loop:
function isEven2($start, $end){
$i = $start;
do {
$i++;
if($i % 2 == 0) {
echo $i. " ";
}
} while ($i < $end);
}
isEven2(1, 20);
// NOTE: It is not possible to print Even numbers in stepping by 2
function isEvenNumbersFor($start, $end, $step) {
for ($i = $start; $i <= $end; $i += $step) {
if ($i % 2 == 0) {
echo $i . " ";
}
}
echo "\n";
}
isEvenNumbersFor(1, 20, 2);
?>