In this blog post, we will walk through a simple C++ program that calculates electricity bills based on the units consumed. This program demonstrates basic concepts of conditional statements, user input, and output in C++. We'll break down the code into smaller sections to understand its functionality step by step.
The Program Code
Breaking Down the Code
1. Header Files and Namespace
#include <iostream>
#include <conio.h>
using namespace std;
#include <iostream>
: This header file is necessary for input-output operations.#include <conio.h>
: This header file is used for console input/output.using namespace std;
: This line allows us to use the standard namespace, simplifying the code.
2. Main Function
int main(){
This is the entry point of our C++ program.
3. Variable Declaration
float unit;
float charge, min_charge = 50.00;
char name[15];
unit
: Stores the number of units consumed.charge
: Stores the calculated charge.min_charge
: Stores the minimum charge, initialized to 50.00.name[15]
: Stores the name of the user (up to 14 characters plus the null terminator).
4. Clear Screen
system("cls");
Clears the screen before taking user input (specific to Windows systems).
5. Taking User Input
cout << "Enter name: ";
cin >> name;
cout << "Enter Unit Consumed: ";
cin >> unit;
- Prompts the user to enter their name and the units of electricity consumed.
cin
is used to take input from the user.
6. Calculating the Charge
The charge is calculated based on the units consumed using conditional statements:
For units less than or equal to 100:
if (unit <= 100){
charge = 0.6 * unit + min_charge;
cout << name << ", your electricity consumption is " << unit << " and your bill is " << charge << " Rs.";
}
The charge is calculated as 0.6 * unit + min_charge
.
For units between 101 and 299:
else if (unit > 100 && unit < 300){
charge = 0.8 * unit + min_charge;
cout << name << ", your electricity consumption is " << unit << " and your bill is " << charge << " Rs.";
}
The charge is calculated as 0.8 * unit + min_charge
.
For units greater than 300:
else if (unit > 300){
charge = 0.9 * unit + min_charge;
if (charge > 300){
charge = charge + charge * 0.15;
cout << name << ", your electricity consumption is " << unit << " and your bill is " << charge << " Rs.";
}
}
The charge is calculated as 0.9 * unit + min_charge
. If the calculated charge exceeds 300, an additional 15% surcharge is applied.
0 Comments