Fungsi Pertambahan dan Pengurangan dalam Bentuk Rekursif dalam Bahasa C

///Kamus

int add_rec(int num1, int num2);

int subs_rec(int num1, int num2);

void cetak(int num1, int num2);

///Fungsi

int add_rec(int num1, int num2)
{
int hasil;

if (num2>0)
{
hasil = add_rec(num1, num2-1)+1;
}
else
{
hasil = num1;
}

return hasil;
}

 

int subs_rec(int num1, int num2)
{
int hasil;

if (num2>0)
{
hasil = subs_rec(num1, num2-1)-1;
}
else
{
hasil = num1;
}

return hasil;
}

void cetak(int num1, int num2)
{
if(num2==0)
{
printf(“%d”,num1);
}
else
{
printf(“1+”);
cetak(num1,num2-1);
}
}

 

///Algoritma

puts(“============ PENAMBAHAN ===============”);
puts(“”);

printf(“5+6 = “);
printf(“%d\n”,add_rec(5,6));
cetak(5,6);
puts(“”);
puts(“”);

printf(“9+3 = “);
printf(“%d\n”,add_rec(9,3));
cetak(9,3);
puts(“”);
puts(“”);

printf(“7+4 = “);
printf(“%d\n”,add_rec(7,4));
cetak(7,4);
puts(“”);
puts(“”);

printf(“8+1 = “);
printf(“%d\n”,add_rec(8,1));
cetak(8,1);
puts(“”);
puts(“”);
puts(“============ PENGURANGAN ===============”);
puts(“”);

printf(“9-2 = “);
printf(“%d\n”,subs_rec(9,2));
cetak(9,2);
puts(“”);
puts(“”);

printf(“7-4 = “);
printf(“%d\n”,subs_rec(7,4));
cetak(7,4);
puts(“”);
puts(“”);

printf(“2-5 = “);
printf(“%d\n”,subs_rec(2,5));
cetak(2,5);
puts(“”);
puts(“”);

printf(“5-5 = “);
printf(“%d\n”,subs_rec(5,5));
cetak(5,5);
puts(“”);
puts(“”);

 

return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *