Professional Documents
Culture Documents
Lab Tasks:
1. Write a function power (a, b), to calculate the value of a raised to b, using:
(a) non-recursive method
(b) recursion
Solution:
#include<stdio.h>
#include<stdio.h>
void calculate_power(int,int);
void main()
{
int a,b;
printf("Insert the value of a\n");
scanf("%d",&a);
printf("Insert the value of b\n");
scanf("%d",&b);
calculate_power(a,b);
}
Execution:
By recursive method:
#include <stdio.h>
int main() {
int a, b, result;
scanf("%d", &b);
return 0;
Execution:
3. Write a recursive function to obtain the running sum of first 25 natural numbers.
Solution:
#include<stdio.h>
int sum(int num);
int recr_sum(int num);
void main()
{
int z;
Execution:
Home Task:
1. The greatest common divisor of integers x and y is the largest integer that evenly divides both
x and y. Write a recursive function GCD that returns the greatest common divisor of x and y.
Solution:
#include <stdio.h>
int hcf(int x, int y);
int main() {
int x, y;
printf("Insert two positive integers: ");
scanf("%d %d", &x, &y);
printf("G.C.D of %d and %d is %d.", x, y, hcf(x, y));
return 0;
}
int hcf(int x, int y) {
if (y != 0)
return hcf(y, x % y);
else
return x;
}
Execution:
2. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence.
Solution:
#include<stdio.h>
int fibon(int num);
void main()
{
int num,z=0,j;
printf("Fibonacci Series:\n");
for(j=1;j<=num;j++)
{
printf("%d\n", fibon(z));
z++;
}
}
int fibon(int num)
{
if(num==0)
{
return 0;
}
else if(num==1)
{
return 1;
}
//fibonacci = 1 1 2 3 5 8
// where n = (n-1) + (n-2)
else
{
return (fibon(num-1)+fibon(num-2));
}
}
Execution:
3. Write a function countEven(int*, int) which receives an integer array and its size and returns
the number of even numbers in the array.
Solution:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int array1[] = {1, 7, 8, 10, 13, 21, 23};
int arr_size = sizeof(array1)/sizeof(array1[0]);
printf("%d",test(array1, arr_size));
}
int test(int nums[], int arr_size)
{
int evens = 0;
for (int i = 0; i < arr_size; i++)
{
if (nums[i] % 2 == 0) evens++;
}
return evens;
}
Execution:
-----------------------------------------------------------------------------------------------------