A tariff program is a useful example of range-based if...else logic. This version calculates the charge by slabs so each unit range is priced separately instead of applying one rate to the entire consumption.
#include <stdio.h>
int main(void) {
double units = 250.0;
double charge;
if (units < 0.0) {
printf("Units cannot be negative.\n");
return 1;
}
if (units <= 100.0) {
charge = units * 1.50;
} else if (units <= 200.0) {
charge = 100.0 * 1.50
+ (units - 100.0) * 2.00;
} else {
charge = 100.0 * 1.50
+ 100.0 * 2.00
+ (units - 200.0) * 3.00;
}
printf("Charge = %.2f\n", charge);
return 0;
}
#include <stdio.h>
int main(void) {
double units;
printf("Enter units consumed: ");
if (scanf("%lf", &units) != 1 || units < 0.0) {
printf("Enter a valid non-negative number.\n");
return 1;
}
double charge;
if (units <= 100.0) {
charge = units * 1.50;
} else if (units <= 200.0) {
charge = 150.0
+ (units - 100.0) * 2.00;
} else {
charge = 350.0
+ (units - 200.0) * 3.00;
}
printf("Total charge = %.2f\n", charge);
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
17-01-2021 | |
REM It's an exam program Print “ ” A= 50 B= 30 C = A * B Print “ The result is “, C | |