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

PHPz
Release: 2024-03-11 09:40:01
Original
553 people have browsed it

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:

Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!