void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } |
#include<stdio.h> int rec (int x); void main() } int rec (int x)
|
return_type function_name( parameter list ) {
body of the function
}
Q5) Explain the difference between function and recursion?A5) ‘declare’, ‘define’ and call a function. You can identify a function as a component of whole program, with a separate body, starting and ending indications, a curly bracket ‘{}’ in case of ‘C’, input parameters and output type being part of it.Eg:
<return type> fooBar(<data type> input_var|,...) {//Body start indicator of a function /* *Some code, which solves the problem *for which the function is designed! */ return <some value of type as return type of the function> |
Eg: int Fact(int n) //Recursive function to calculate factorial of n { if(n==0 || n==1) //Terminating condition return 1; return n * fact(n-1); //Recursion statement(condition calling itself) } |
#include <stdio.h>
// An example function that takes two parameters 'x' and 'y' // as input and returns max of two input numbers int max(int x, int y) { if (x > y) return x; else return y; } |
// main function that doesn't receive any parameter and // returns integer. int main(void) { int a = 10, b = 20;
| ||
// Calling above function to find max of 'a' and 'b' int m = max(a, b);
printf("m is %d", m); return 0; | ||
} | ||
#include <stdio.h> /** * Function to check even or odd * Returns 1 is num is even otherwise 0 */ int isEven(int num) { return !(num & 1); } int main() { int num; /* Input number from user */ | |
printf("Enter any number: "); scanf("%d", &num);
/* If isEven() function returns 0 then the number is even */ if(isEven(num)) { printf("The number is even."); } else { printf("The number is odd."); } return 0; } | |
#include <stdio.h> #include <string.h> int main() { char s[100]; printf("Enter a string to reverse\n"); | ||
gets(s); strrev(s); printf("Reverse of the string: %s\n", s); return 0; } | ||
#include <stdio.h> int main() { int i, num1, num2, max, lcm=1; | ||||
/* Input two numbers from user */ printf("Enter any two numbers to find LCM: "); scanf("%d%d", &num1, &num2); /* Find maximum between num1 and num2 */ max = (num1 > num2) ? num1 : num2; /* First multiple to be checked */ i = max; /* Run loop indefinitely till LCM is found */ while(1) { if(i%num1==0 && i%num2==0) printf("Enter any two numbers to find LCM: "); scanf("%d%d", &num1, &num2); /* Find maximum between num1 and num2 */ max = (num1 > num2) ? num1 : num2; /* First multiple to be checked */ i = max; /* Run loop indefinitely till LCM is found */ while(1) | ||||
{ if(i%num1==0 && i%num2==0) { /* * If 'i' divides both 'num1' and 'num2' * then 'i' is the LCM. */ lcm = i; /* Terminate the loop after LCM is found */ break; } /* * If LCM is not found then generate next * multiple of max between both numbers */ i += max; } printf("LCM of %d and %d = %d", num1, num2, lcm); return 0; } | ||||