1.Write a function to input electricity unit charges and calculate total electricity bill according to the given condition:
a. For first 50 units Rs. 0.50/unit
b. For next 100 units Rs. 0.75/unit
c. For next 100 units Rs. 1.20/unit
d. For unit above 250 Rs. 1.50/unit
Answer
#include <stdio.h>
float calculateElectricityBill(int units);
float calculateElectricityBill(int units)
{
float bill = 0.0;
if (units <= 50)
bill=0.5*units;
else if (units<=150)
bill=0.5*50+(units-50)*0.75;
else if (units<=250)
bill=0.5*50+0.75*100+(units-150)*1.20;
else{
bill=0.5*50+0.75*100+1.20*100+(units-250)*1.50;
bill += units * 1.50;
}
return bill;
}
int main()
{
int units;
float bill;
printf("Enter the number of units: ");
scanf("%d", &units);
bill = calculateElectricityBill(units);
printf("Total electricity bill: Rs. %.2f\n", bill);
return 0;
}
2.Write a function to convert the LKR currency into US dollars.
Answer
#include <stdio.h>
float us_dollars(float lkr);
float us_dollars(float lkr) {
float us_value;
us_value = lkr / 312.94;
return us_value;
}
int main() {
float lkr, us_value;
printf("Enter the LKR value: ");
scanf("%f", &lkr);
us_value = us_dollars(lkr);
printf("Value in US dollars: %.2f\n", us_value);
return 0;
}
3. Write a function to return the trip cost which calculated using the given distance in kilometers.
5. Calculate the power of a number using a recursive function.
Answer
#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;
}
6. Find sum of natural numbers using a recursive function.
Answer
#include <stdio.h>
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;
}
0 Comments