Find Sum of N Numbers using Recursion
#include
#include
void display(int);
int main()
{
int num, result;
printf("Enter the Nth number: ");
scanf("%d", &num);
display(num);
return 0;
}
void display(int num)
{
static int i = 1;
if (num == i)
{
printf("%d \n", num);
return;
}
else
{
printf("%d ", i);
i++;
display(num);
}
}
Output
Enter the Nth number: 10
1 2 3 4 5 6 7 8 9 10
Find HCF of a given Number using Recursion
#include
#include
int hcf(int, int);
int main()
{
int a, b, result;
clrscr();
printf("Enter the two numbers to find their HCF: ");
scanf("%d%d", &a, &b);
result = hcf(a, b);
printf("The HCF of %d and %d is %d.\n", a, b, result);
}
int hcf(int a, int b)
{
while (a != b)
{
if (a > b)
{
return hcf(a - b, b);
}
else
{
return hcf(a, b - a);
}
}
return a;
}
Output
Enter the two numbers to find their HCF: 24 36
The HCF of 24 and 36 is 12.
Find Power of a Number using Recursion
#include
#include
long power (int, int);
int main()
{
int pow, num;
long result;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter it's power: ");
scanf("%d", &pow);
result = power(num, pow);
printf("%d^%d is %ld", num, pow, result);
return 0;
}
long power (int num, int pow)
{
if (pow)
{
return (num * power(num, pow - 1));
}
return 1;
}
Output
Enter a number: 456
Enter it's power: 3
456^3 is 94818816
Perform Quick Sort on a set of Entries from a File using
Recursion
#include
#include
void quicksort (int [], int, int);
int main()
{
int list[50];
int size, i;
clrscr();
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
Output
Enter the number of elements: 6
Enter the elements to be sorted:
67
45
24
98
12
38
After applying quick sort
12 24 38 45 67 98
No comments:
Post a Comment