LearnFrenzy
Sign in Take a free test

Control Instructions · Decision Making Programs · Question 3

Electricity bill calculation with slabs in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Compute a bill: the first 100 units at Rs. 3.00, the next 100 at Rs. 4.50, the next 100 at Rs. 6.00, everything above 300 at Rs. 7.50, plus a fixed charge of Rs. 50.

Solution
main.c
#include <stdio.h>

double bill(int units) {
    double amount = 0;
    if (units > 300) {
        amount += (units - 300) * 7.50;
        units = 300;
    }
    if (units > 200) {
        amount += (units - 200) * 6.00;
        units = 200;
    }
    if (units > 100) {
        amount += (units - 100) * 4.50;
        units = 100;
    }
    amount += units * 3.00;
    return amount + 50;                         /* fixed charge */
}

int main(void) {
    int tests[] = {80, 150, 350};
    for (int i = 0; i < 3; i++)
        printf("%d units: Rs. %.2f\n", tests[i], bill(tests[i]));
    return 0;
}

Output Verified by compiling and running

80 units: Rs. 290.00
150 units: Rs. 575.00
350 units: Rs. 1775.00

Working from the top slab down, each if charges only the units inside its slab and caps the rest. 350 units = 300 + 450 + 600 + 375 + 50 = 1775.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links