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:
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!