long add_odd(int start, int end);
void main() { int start, end;
do { printf(\"Enter 2 odd numbers : \"); scanf(\"%d%d\ if(start%2==0 || end%2==0)
printf(\"\\n\\aERROR: You have to enter two ODD number\\n\"); if(start>end)
printf(\"\\n\\aERROR: The 1st number should be smaller than the 2nd one\\n\"); }while(start%2==0 || end%2==0 || start>end);
printf(\"Add odd number from %d to %d is : %ld\\n\add_odd(start, end) ); }
<1> Function Using Iteration : long add_odd(int start, int end) { long total=0;
while(start<=end)
{ total=total+start; end+=2; }
return total; }
main : add_odd(-1,5) <2> Function Using Recursion : long add_odd(int start, int end) function {
}
4
X To The POWER Of Y Question : Following is a program to calculate x to the power of y using iteration. Rewrite the iterative function( power() ) by a recursive function.
#includevoid get_input(int *base, int *pow); double power(int base, int pow);
main() {
int base, pow, temp=0; double total;
get_input(&base, &pow); if (pow<=0 && base==0)
printf(\"The result is undefined\\n\"); else
{ if (pow<0)
total=power(base, -pow); else
total=power(base, pow); if (pow<0) total=1/total;
printf(\"%d to the power of %d is %lf\\n\" ,base, pow, total); }
return 0; }
OUTPUT : Enter Base : -> 2 Enter Base : -> -2
Enter Power : -> 7 Enter Power : -> -2
2 to the power of 7 is 128.000000 -2 to the power of 2 is 0.250000
Function Using Recursion :double power(int base, int pow) main : power(2,3) { function :
}
5
More On RECURSION#include #includevoid reverse(char *string, int size);
main()
{ char string[20];
gets(string);
reverse(string, strlen(string)); printf(\"%s\\n\ return 0; }
main : reverse(“abcde”, 5) function : string reverse(“abcde”, 5) void reverse(char *string, int size) { char temp; a b c d e \\0 e b c d a \\0
if (size<2) [0] [1] [2][3] [4][5] [0][1] [2] [3] [4][5] return;
else string reverse(“bcda”, 3) { temp=string[0]; string[0]=string[size-1]; e b c d a \\0 e d c b a \\0
string[size-1]=temp; [0][1] [2][3] [4][5] [0][1] [2] [3][4][5] reverse(string+1, size-2);
} string reverse(“cda”, 1) }
e b c d a \\0 e d c b a \\0
[0][1] [2][3] [4][5] [0] [1] [2] [3][4][5]
terminating case : size of string == 0/1
[0] [1] [2] … [ ] [size-1] general case : reserve(string+1, size-2)
6