Home  >  Article  >  Backend Development  >  Tutorial: Write a program in PHP to output odd numbers within 100

Tutorial: Write a program in PHP to output odd numbers within 100

PHPz
PHPzOriginal
2024-03-11 09:39:03609browse

Tutorial: Write a program in PHP to output odd numbers within 100

In this article, I will introduce to you how to use PHP to write a program to output all odd numbers within 100. If you are interested in PHP programming, then this article will be helpful to you.

First of all, we need to understand the loop structure and conditional statements in PHP. In this task, we will use for loop and if statement to achieve our goal.

First, we open a text editor and create a new PHP file named oddNumbers.php.

Next, we start writing our program. Here is the complete PHP code example:

<?php
// 使用 for 循环遍历 1 到 100 的所有数字
for ($i = 1; $i <= 100; $i++) {
    // 使用 if 语句判断当前数字是否为奇数
    if ($i % 2 != 0) {
        // 如果是奇数,则输出该数字
        echo $i . " ";
    }
}
?>

Let us explain the above code in detail:

  1. We use a for loop to iterate through all the numbers from 1 to 100, $i is a counter, initialized to 1 and incremented by 1 each loop until it reaches 100.
  2. In each iteration of the loop, first use an if statement to check whether the current number $i is odd. The way to tell if a number is odd is to see if the remaining digits are not equal to 0. If the remainder of $i divided by 2 is not equal to 0, then it is an odd number.
  3. If the current number $i is an odd number, we use the echo statement to output the number, and add a space after the output so that the numbers can be correctly separated.

Finally, save and run this PHP file, you will see the output is 1 3 5 7 9 ... 97 99. These are the results of outputting all odd numbers within 100.

Through this simple PHP program example, we can see how to use for loops and if statements to filter out specific types of numbers within a certain range. I hope this article is helpful to you, and I hope it can stimulate your interest in PHP programming. Good luck with your programming!

The above is the detailed content of Tutorial: Write a program in PHP to output odd numbers within 100. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn