Function and Recursive
ola
you might think when learning about function it's a hard part of programming but fret not for it is an easy process and it'll make your programs a lot more cleaner and tidier.
when defining a function you may use any data types as long as you're able to use return, if for some reason you don't want to use return you might find void data type a lot more useful. don't forget whenever you want to use function you'll also need parameter in it.
int functionName( int parameter1, int parameter2, ...){
some program;
return;
}
int main(){
someVariable = functionName(para1,para2,...);
return 0;
}
that's the basic when calling an int based function
void funcName(int para1, int para2, ...){
some program
}
int main(){
funcName(para1,para2,...);
return 0;
}
when using void you don't need th return command as the function will do everything inside it.
now what about recursive.?????
all you have to know about recursive is that recursive is a function that calls itself over and over again until it stops.
basic recursive for factorial is
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
just remember to have a way to stop your function from doing recursive forever.
you might think when learning about function it's a hard part of programming but fret not for it is an easy process and it'll make your programs a lot more cleaner and tidier.
when defining a function you may use any data types as long as you're able to use return, if for some reason you don't want to use return you might find void data type a lot more useful. don't forget whenever you want to use function you'll also need parameter in it.
int functionName( int parameter1, int parameter2, ...){
some program;
return;
}
int main(){
someVariable = functionName(para1,para2,...);
return 0;
}
that's the basic when calling an int based function
void funcName(int para1, int para2, ...){
some program
}
int main(){
funcName(para1,para2,...);
return 0;
}
when using void you don't need th return command as the function will do everything inside it.
now what about recursive.?????
all you have to know about recursive is that recursive is a function that calls itself over and over again until it stops.
basic recursive for factorial is
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
just remember to have a way to stop your function from doing recursive forever.
Comments
Post a Comment