Membuat Deret Bilangan Ganjil/Genap dengan Script PHP (Rekursif)

richard maulana
Sep 5, 2018 · 1 min read

Berikut ini adalah script php deret bilangan ganjil dan genap menggunakan fungsi rekursif :

<h1> BILANGAN GANJIL GENAP </h1>

<form action=" " method="GET">
Banyak : <input type ='text' name ='banyak'><br><br>
Bilangan : <select name='bil'>
<option value ='ganjil'>Ganjil</option>
<option value ='genap'>Genap</option>
</select><br>
<br><input type='submit' name='tampil' value='tampil'>
</form>

<?php

if(isset($_GET['tampil'])){ //isset :sebuah variable yang memberi tahu sudah diset atau belum

$bil = $_GET['bil'];
$banyak=$_GET['banyak'];

function ganjil($a,$b=0,$c=0){
if($b<$a){
if($b==0){
echo $c+=1;
}else
echo $c+=2;
echo ",&nbsp";
$b++;
ganjil($a,$b,$c);
}
}

function genap($a,$b=0,$c=0){
if($b<$a){
if($b==0){
echo $c+=2;
echo ",&nbsp";
}else
echo $c+=2;
echo ",&nbsp";
$b++;
genap($a,$b,$c);
}
}

switch ($bil){
case "ganjil":
echo "Deret Bilangan Ganjil : ";
ganjil($banyak);
break;
case "genap":
echo "Deret Bilangan Genap : ";
genap($banyak);
break;
default:
break;
}
}
?>

Dimana Outputnya seperti gambar dibawah ini :

Saat inputan di isi 5 maka akan menghasilkan deret ganjil sebanyak 5 angka

    richard maulana

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade