Recursion in c Programs

Read tutorials from Recursion in c


Program List:


Long Program Share

Program:

#include<stdio.h>
float power(float a , int n);
float Ipower(float a , int n);
main( )
{
float a, p;
int n;
printf("Enter a and n : ");
scanf("%f %d", &a, &n);
p = power(a, n);
printf("%f raised to power %d is %f\n", a, n, p);
p = Ipower(a, n);
printf("%f raised to power %d is %f\n", a, n, p);
}/*End of main()*/

/*Recursive*/
float power(float a , int n)
{
if(n == 0)
return(1);
else
return(a * power(a,n-1));
}/*End of power()*/

/*Iterative*/
float Ipower(float a , int n)
{
int i;
float result=1;
for(i=1; i<=n; i++)
result = result * a;
return result;
}/*End of Ipower()*/

Output:


Enter a and n : 1.2
2
1.200000 raised to power 2 is 1.440000
1.200000 raised to power 2 is 1.440000
Press any key to continue . . .


Long Program Share

Program:

#include<stdio.h>
void display(long int n);
void Rdisplay(long int n);
int sumdigits( long int n);
main( )
{
long int num;
printf("Enter number : ");
scanf("%ld", &num);
printf("%d\n",sumdigits(num));
printf("\n");
display(num);
printf("\n");
Rdisplay(num);
printf("\n");
}/*End of main()*/

/*Finds the sum of digits of an integer*/
int sumdigits(long int n)
{
if( n/10 == 0 ) /* if n is a single digit number*/
	return n;
return n%10 + sumdigits(n/10);
}/*End of sumdigits()*/

/*Displays the digits of an integer*/
void display(long int n)
{
if( n/10==0 )
	{
	printf("%d",n);
	return;
	}
display(n/10);

printf("%d",n%10);
}/*End of display()*/

/*Displays the digits of an integer in reverse order*/
void Rdisplay(long int n)
{
if(n/10==0)
	{
	printf("%d",n);
	return;
	}
printf("%d",n%10);

Rdisplay(n/10);
}/*End of Rdisplay()*/

Output:


Enter number : 10
1

10
01
Press any key to continue . . .


Long Program Share

Program:

#include<stdio.h>
void convert(int, int);
main()
{
int num;
printf("Enter a positive decimal number : ");
scanf("%d", &num);
convert(num, 2);
printf("\n");
convert(num, 8);
printf("\n");
convert(num, 16);
printf("\n");
}/*End of main()*/

void convert (int num, int base)
{
int rem = num%base;
if(num==0)
	return;
	
convert(num/base, base);

	if(rem < 10)
	printf("%d", rem);
	else
	printf("%c", rem-10+'A' );
}/*End of convert()*/

Output:


Enter a positive decimal number : 6
110
6
6
Press any key to continue . . .