Skip to content

Lab · Rust Programming

Lab: an electricity bill with slab rates

Labbeginner· about 1.5 hours· 5 steps

The brief

Build a small command-line bill calculator for homes in a housing society. Electricity is charged in slabs (example rates: the first 100 units at Rs 3, units 101 to 300 at Rs 5, above 300 at Rs 8, plus a fixed Rs 50). You write the slab function, return the bill as a tuple, summarise six months stored in arrays, and read this month's units from the keyboard without crashing on typos.

Why it matters

Slab pricing is everywhere in India: electricity, water, mobile data, income tax. Getting the boundaries right (is unit 100 in the first slab or the second?) is exactly the kind of logic a developer is paid to get right, and reading and checking user input is part of every tool you will write.

Skills you practise

  • u32 arithmetic
  • functions with return values
  • if / else if / else
  • tuples and destructuring
  • arrays and for loops
  • std::io::stdin, trim and parse with match
  • loop and continue

You need

  • Rust stable installed with rustup
  • A terminal (bash, zsh, Git Bash or PowerShell)

What you will have at the end

A power_bill cargo project: a slab calculator with a tuple-returning bill function, a six-month summary from arrays and safe keyboard input.

How it is marked (rubric, 100 points)
Correct slabs and totalsAll printed amounts match, including the slab boundaries at 100 and 300 units.40
Functions and typesenergy_charge and bill are small functions with typed parameters and return values; the tuple is destructured.25
Safe inputtrim and parse with match, a loop that asks again, and a new String for every read.25
Readable codeClear names, a FIXED_CHARGE constant, no warnings.10

0/5 steps done

Step 1 of 5

The slab function

energy_charge(units) returns the right charge for 0, 80, 150 and 320 units.

Create the project with cargo new power_bill and copy in the starter. Each slab charges only the units inside it: 150 units is 100 x 3 plus 50 x 5 = 550, not 150 x 5. Write energy_charge with if / else if / else and let the last expression of each branch be the result (no semicolon, no return needed). In main, loop over the array [0, 80, 150, 320] with for and print one line per value.

Run this on your machine, then paste the output below
$ cargo run
Your notes: src/main.rs

Write down each command you ran. It goes into your project summary.