1
0

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 1 year has passed since last update.

【PHP初級㉗】range関数、array_sum関数

Last updated at Posted at 2022-07-07

[問題]   (参照:http://www.cc.kyoto-su.ac.jp/~mmina/bp1/hundredKnocksPrimary.html)
整数値を入力させ、1からその値までの総和を計算して表示するプログラムを作成しなさい。
ただし、0以下の値を入力した場合は0と表示する。

コード

$a = intval(fgets(STDIN));
$m = range(1, $a);
if($a > 0){
    echo array_sum($m);
}else{
    echo '0';
}

↓「6」と入力

結果

21

☆range()
・・・ある範囲の整数を有する配列を作成する関数。

例)range(1,10)  →  1から10までの整数の配列

☆array_sum()
・・・配列の中の値の合計を計算する関数。

例)

$a = [2,3,4];
echo array_sum($a);

     ↓ 結果

9
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?