Showing posts with label Recurrsion. Show all posts
Showing posts with label Recurrsion. Show all posts

Saturday, December 5, 2009

PROGRAM TO CHECK PALINDROME OF STRING USING RECURRSION

#include "stdio.h"
#include "conio.h"
#include "string.h"

int palindrome(char *string)
{
int len;
char first, last;
len = strlen(string);
if(len == 1 || len == 0)
return 1; //palindrome

first = string[0]; //first character of string
last = string[len-1];//last character of string
if(first == last)
{
/*delete first and last characters -- extract the middle
portion of string */

for(int i=0; i string[i] = string[i+1];//this deletes first char

//now delete last char
string[len-2] = '\0';

return palindrome(string);
}

return 0; //not palindrome
}


int main()
{
char str[30];
clrscr();
printf("\nEnter a string: ");
gets(str);

if(palindrome(str))
printf("\nPalindrome.");
else
printf("\nNot palindrome");

getch();
return 0;
}

FIBONACCI SERIES USING RECURRSION

#include "stdio.h"
#include "conio.h"

long int fib(int); /* Function Prototype */

void main()
{
int n,i;
long int result;
printf("Enter Nth Term : ");
scanf("%d",&n);

i = 0;
while(i < n)
{
result = fib(i++); /* function Call */
printf("%ld\t",result);
}

getch();
}
/* End of Main */

long int fib(int m) /* Function Definition */
{
if (m == 0) /* Control Statements for Recurrsion */
return 0;
else if(m == 1 || m == 2)
return 1;
else
return fib(m-1) + fib(m-2); /* Recursive Statement */
}
/* End of Program */

PROGRAM TO FIND THE SUM OF DIGITS USING RECURRSION

#include "stdio.h"
#include "conio.h"

int sum(long int);/* Function Prototype */

void main()
{
long int num;
int result;
printf("Enter Number :");
scanf("%ld",&num);
result = sum(num); /* Function Call */
printf("Sum of Digits - %d",result);
getch();
}

int sum(long int n) /* Function Definition */
{
int digit;
if(n == 0)
return 0;
else
{
digit = n%10;
return digit + sum(n/10); /* Recursive Statement */
}
}

Friday, June 26, 2009

PROGRAM TO PRINT THE REVERSE OF ENTERED STRING

#include "stdio.h"
#include "conio.h"

void reverse(void);

void main()
{
clrscr();
printf("Write Something...\n");
reverse();
getch();
}

void reverse(void)
{
char ch;

if((ch=getchar())!='\n')
reverse();

putc(ch,stdout);
}


by Ankit Pokhrel.