recursions

 1. Srujan asks his son Arun to calculate the sum of total natural numbers present on the board. 

Arun starts summing the natural numbers and after reaching up to 10 he gets confused and 

again starts counting from first. Your task is to help Arun to calculate the sum of n natural 

numbers recursively

Sol: 

 #include<stdio.h>

 int sum(int n);

 int main()

 {

 int n;

 scanf("%d",&n);

 printf("sum of natural numbers=%d\t",sum(n));

 return 0;

 }

 int sum(int n)

 {

 if(n==0)

 {

return 0;

 }

 else if(n==1)

 {

 return 1;

 }

 else

{

return (n+sum(n-1));

}

}

2.Write a recursive module to find factorial of a given number.

Sol:

 #include<stdio.h>

 long int fact(int n);

 int main()

 {

 int n;

 scanf("%d",&n);

 printf("factorial of a given number=%ld",fact(n));

 return 0;

 }

 long int fact(n)

 {

if(n==0||n==1)

 {

return 1;

 }

 else

 {

return(n*fact(n-1));

 }

 }

3.Two kids are playing with each other. Game is one must give any integer number and the other 

must count the number of digits that number contains. Your task is to develop a program to 

count the digits of a number using recursion

4. Write a program in C to count the digits of a given number using recursion. Example: Input a 

number : 50 Expected Output : The number of digits in the number is : 2

Sol : 

 #include<stdio.h>

int countdigit(int n);

int main()

{

int n;

scanf("%d",&n);

printf("digits count=%d",countdigit(n));

return 0;

}

int countdigit(int n)

{

static int count=0;

if(n>0)

{

count++;

countdigit(n/10);

}

else

{

return count;

}

}

5. In mathematics, finding the GCD of a number is quite interesting. Hari is a genius in programming, 

he wants to find the GCD of a number using his programming skills. Your task is to help Hari in 

getting GCD of a number recursively with possible test cases.

Sol:

#include<stdio.h>

int gcd(int a,int b);

int main()

{

int a,b;

scanf("%d%d",&a,&b);

printf("\n the gcd of given number=%d",gcd(a,b));

return 0;

}

int gcd(int a,int b)

{

if(b!=0)

{

return(gcd(b,a%b));

}

else

{

return a;

}

}

6. Write a C program to print Fibonacci series using recursive function

Sol:

 #include<stdio.h>

 int fib(int n);

 int main()

 {

 int n,i;

 scanf(“%d”,&n);

 for(i=0;i<n;i++)

 {

 printf(“%d\t”,fib(i));

 } 

 return 0;

 }

 int fib(int n)

 {

 if(n==0)

 return 0;

 else if(n==1)

 return 1;

 else

 return (fib(n-1)+fib(n-2));

 } 

Comments

Popular posts from this blog

1d array

strings

2d array