Tutorial 12
02. Display all prime numbers between two Intervals using a function.
#include <stdio.h>
int number(int);
int number (int n)
{
int a,b,c=0;
for (a=1; a<=n; a++)
{
if (n%a==0)
c=c+1;
}
if (c<=2)
printf("%i It is a prime number\n",n);
else
printf("%i It is not a prime number\n",n);
return;
}
int main ()
{
int x,y,n;
printf("Enter Number");
scanf("%i", &x);
printf("Enter Number");
scanf("%i", &y);
for (x; x<=y; x++)
number(x);
return 0;
}
03. Find sum of natural numbers using a recursive function.
int sum_of_natural_numbers(int n)
{
if (n == 0)
{
return 0;
}
else
{
return n + sum_of_natural_numbers(n - 1);
}
}
int main()
{
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0)
{
printf("Please enter a positive integer.\n");
return 1;
}
printf("Sum of first %d natural numbers is: %d\n", num, sum_of_natural_numbers(num));
return 0;
}
04. Calculate the power of a number using a recursive function.
#include <stdio.h>
double power(double base, int exponent)
{
if (exponent == 0)
{
return 1;
}
else if (exponent > 0)
{
return base * power(base, exponent - 1);
} else {
return 1 / power(base, -exponent);
}
}
int main() {
double base;
int exponent;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
printf("Result: %.2lf\n", power(base, exponent));
return 0;
}
05. Write a function to return the trip cost which calculated using the given distance in kilometers. Note: Take 35 LKR as travelling cost per kilometer.
#include <stdio.h>
double calculate_trip_cost(double distance) {
const double cost_per_km = 35.0;
return distance * cost_per_km;
}
int main() {
double distance;
printf("Enter the distance in kilometers: ");
scanf("%lf", &distance);
printf("Trip cost: %.2lf LKR\n", calculate_trip_cost(distance));
return 0;
}
06. Write a function to convert the LKR currency into US dollars.
#include <stdio.h>
double lkr_to_usd(double lkr_amount, double exchange_rate)
{
return lkr_amount / exchange_rate;
}
int main()
{
double lkr_amount, exchange_rate;
printf("Enter the amount in LKR: ");
scanf("%lf", &lkr_amount);
printf("Enter the exchange rate (LKR to USD): ");
scanf("%lf", &exchange_rate);
printf("%.2lf LKR is equal to %.2lf USD\n", lkr_amount, lkr_to_usd(lkr_amount, exchange_rate));
return 0;
}