lundi 26 octobre 2020

the code keep printing same word two times

That's what I am trying to do:

  • Output the numbers from 1 to 100

• Where the number is divisible by three (3) output the word “foo”

• Where the number is divisible by five (5) output the word “bar”

• Where the number is divisible by three (3) and (5) output the word “foobar”

I was able to do that, but it is printing two times foobar as shown in the output below rather just once. What am I doing wrong?

My code:

<?php

for ($i = 1; $i<=100; $i++) {
    if ($i % 3 && $i % 5) {
        echo $i;
    } else {
        if ($i % 3 == 0) {
            echo "foo";
        }
        if ($i % 5 == 0) {
            echo "bar";
        }
        if ($i % 3 == 0 && $i % 5 == 0) {
            echo "foobar\r\n";
        }
    }
    //line breaks to enhance output readability
    echo "\r\n";
}

?>

Output:

task2 % php foobar.php
1
2
foo
4
bar
foo
7
8
foo
bar
11
foo
13
14
foobarfoobar

16
17
foo
19
bar
foo
22
23
foo
bar
26
foo
28
29
foobarfoobar

31
32
foo
34
bar
foo
37
38
foo
bar
41
foo
43
44
foobarfoobar

46
47
foo
49
bar
foo
52
53
foo
bar
56
foo
58
59
foobarfoobar

61
62
foo
64
bar
foo
67
68
foo
bar
71
foo
73
74
foobarfoobar

76
77
foo
79
bar
foo
82
83
foo
bar
86
foo
88
89
foobarfoobar

91
92
foo
94
bar
foo
97
98
foo
bar

Aucun commentaire:

Enregistrer un commentaire