PHP finds odd and even numbers and multiple methods

WBOY
Release: 2016-07-25 09:13:20
Original
9550 people have browsed it

Example 1, find the sum of odd numbers between 0--100

  1. php
  2. $sum=0;
  3. for($i=0;$i<=100;$i++) {
  4. if($i%2==1){
  5. $sum+=$i;
  6. } }
  7. echo $ sum;
  8. ?>
  9. Copy code
Example 2, find the sum of even numbers between 0--100

Find even sum--bbs.it-home.org
  1. < ?php
  2. $sum=0;
  3. for($i=0;$i<=100;$i+=2) {
  4. $sum+=$i;
  5. }
  6. echo $sum;
  7. ?>
  8. Copy code
Method 2: ? php
function getSums($num = 100){$sum1 = 0;$sum2 = 0;
for($i=0;$i<=$num;$i++){

if($i%2= =0){

$sum1 += $i;
}else{
$sum2 += $i;
    }
  1. }
  2. echo $num."Odd sum within: $sum2; Even sum: $sum1";
  3. }
  4. getSums();
  5. echo "

    ";

  6. getSums(120); //Actual parameters? //This is to find the sum of odd and even numbers within 120
  7. ?>
  8. < /html>
  9. Copy code
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
Popular Tutorials
More>
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!