2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

forループの練習問題(数字でピラミッドを作る)  上級・解答編

Posted at

#問題
下記のリンクの練習問題の解答(PHPで記述)になります。
http://qiita.com/takuya-kodama/items/5a1dd8da56e7a87ec58f

解答よりも良いコードがありましたらコメント等で教えていただければと思います!

#解答

answer.php
<?php

#問題1
for($a = 1 ; $a <= 3; $a++){
  for($b = 4; $b >= $a+1 ; $b--){
    echo $b-$a;
  }
  echo "<br />";
}

#問題2
for($a = 3 ; $a >= 1 ; $a --){
  for($c = 2 ; $c >= $a ; $c --){
    echo "*";
  }

  for($b = 1 ; $b <= $a ; $b ++){
    echo $b;
  }
  echo "<br />";
}

#問題3
$x = 6;
for($a =1 ; $a <= 3 ; $a ++){
  for($b = 1 ; $b<= $a ; $b++){
    echo $x;
    $x --;
  }
  echo "<br />";
}

#問題4
for($a = 4 ; $a >= 1 ; $a--){
  for($b = 3 ; $b >= $a ; $b--){
    echo "*";
  }
  for($c = 1 ; $c <=$a ; $c++){
    echo $c;
  }
  for($d = $c-2 ; $d >=1  ; $d --){
    echo $d;
  }
  echo "<br />";
}


#問題5
for($a = 1 ; $a <= 9 ; $a ++){
  if($a <= 5){
    for($b = 4 ; $b >= $a ; $b --){
      echo "*";
    }
    for($c = 1; $c <= $a ; $c++){
      echo $c;
    }
    for($d =$c -2 ; $d >= 1 ; $d--){
      echo $d;
    }
    echo "<br />";
  }
  else if($a >=6 ){
    for($e = 6 ; $e <= $a ; $e++){
      echo "*";
    }
    for($f = 1 ; $f <=10-$a  ; $f++){
      echo $f;
    }
    for($g = $f-2 ; $g >=1  ; $g --){
      echo $g;
    }
  echo "<br />";
  }
}

#問題6
for($a = 5 ; $a >= 1 ; $a --){
  for($b = 2 ; $b <= $a; $b ++){
    echo "*";
  }
  for($c = 5 ; $c >= $a ;$c --){
    echo $c;
  }
  for($d = $c+2 ; $d <= 5   ; $d ++){
    echo $d;
  }
  echo "<br />";
}


?>

2
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?