Fundamentals of Computer Programming - Old Questions
8. What is recursion? Write a program to find the factorial of given number using recursion. [2+4]
OR
What is pointer? Write a program to sort 'n' numbers in ascending order using dynamic memory. [2+4]
Answer
AI is thinking...
A function that calls itself is known as a recursive function. And, this technique is known as recursion.
Program to find the factorial of given number using recursion:
#include<stdio.h>
int fact(int);
int main()
{
int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);
x=fact(n);
printf(" Factorial of %d is %d",n,x);
return 0;
}
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
____________________________
OR Part:
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
program to sort 'n' numbers in ascending order using dynamic memory:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,n,i,j,t;
printf("How many numbers you want to be sorted: ");
scanf("%d",&n);
a=(int *)malloc(n *sizeof(int));
printf("\\nEnter %d Numbers: \\n\\n",n);
for(i=0;i<=n-1;i++)
{
scanf("%d", (a+i));
}
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
if(*(a+i)<*(a+j))
{
t=*(a+i);
*(a+i)=*(a+j);
*(a+j)=t;
}
}
}
printf("\\nAfter Sorting in Ascending Order: \\n");
for(i=0;i<n;i++)
printf("\\n%d",*(a+i));
return 0;
}