Function and Recursion
function
-> is made to do a special task. for example to calculate numbers.
function and recursion doesn't have much in different, the only different is, in recursion you could call your own function. recursion is a part of function.
syntax:
<dataType> <funstionName> {
<statements>
}
and if you're going to use it, all you have to do is call them.
example:
int sum(int x, int y) {
return x+y;
}
int main() {
int a = 5;
int b = 7;
printf("%d\n", sum(a, b);
return 0;
}
and for recursion:
int fi(int n) {
//base case
if(n == 0) return 0;
if(n == 1) return 1;
else return fi(n-1) + fi(n-2); //they're calling their own function, fi(n-1) and fi(n-2) it means they're going to loop as long as they haven't met all the base case condition.
}
int main() {
int a = 0;
printf("input a number: ");
scanf("%d", &a);
printf("%d\n", fi(a));
return 0;
}
function
-> is made to do a special task. for example to calculate numbers.
function and recursion doesn't have much in different, the only different is, in recursion you could call your own function. recursion is a part of function.
syntax:
<dataType> <funstionName> {
<statements>
}
and if you're going to use it, all you have to do is call them.
example:
int sum(int x, int y) {
return x+y;
}
int main() {
int a = 5;
int b = 7;
printf("%d\n", sum(a, b);
return 0;
}
and for recursion:
int fi(int n) {
//base case
if(n == 0) return 0;
if(n == 1) return 1;
else return fi(n-1) + fi(n-2); //they're calling their own function, fi(n-1) and fi(n-2) it means they're going to loop as long as they haven't met all the base case condition.
}
int main() {
int a = 0;
printf("input a number: ");
scanf("%d", &a);
printf("%d\n", fi(a));
return 0;
}
Comments
Post a Comment