C++ Variables, Data Types and Input
Variables are named containers that hold data, like a name, a price or a score.
Declaring Variables
Write the type, the name and (usually) a starting value:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Bilal";
int age = 22;
double salary = 55000.75;
char grade = 'B';
bool isStudent = true;
cout << name << " is " << age << " years old\n";
cout << "Salary: " << salary << "\n";
cout << "Grade: " << grade << "\n";
cout << "Student: " << isStudent << "\n";
return 0;
}Bilal is 22 years old Salary: 55000.8 Grade: B Student: 1
Two things to notice:
coutshows about 6 significant digits by default, so 55000.75 is shown as 55000.8boolvalues print as1(true) and0(false). Addcout << boolalpha;to printtrueandfalse
Data Types
| Type | Stores | Example |
|---|---|---|
int | Whole numbers | int rooms = 3; |
double | Decimal numbers | double kg = 2.5; |
float | Decimals, less precise | float r = 1.5f; |
char | One character | char c = 'Z'; |
bool | true or false | bool done = false; |
string | Text (needs <string>) | string city = "Hyderabad"; |
Constants and auto
Example
const double GST = 0.18; // cannot be changed later
auto count = 10; // the compiler decides: int
auto rate = 2.75; // the compiler decides: doubleUse const for values that should never change, like tax rates or the number of days in a week. The compiler will stop you if you try to change them by mistake.
Type Conversion
Dividing two int values drops the decimal part. Use static_cast to convert:
Example
#include <iostream>
using namespace std;
int main() {
int total = 7;
int parts = 2;
cout << total / parts << "\n";
cout << static_cast<double>(total) / parts << "\n";
return 0;
}3 3.5
Formatting Decimals
Include <iomanip> to control how many digits are shown:
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double bill = 1234.5;
cout << fixed << setprecision(2) << bill << "\n";
return 0;
}1234.50
Reading Input with cin
cin >> reads a value typed by the user:
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int year;
cout << "Your name: ";
cin >> name;
cout << "Birth year: ";
cin >> year;
cout << "Hi " << name << ", you are about " << 2026 - year << " years old.\n";
return 0;
}Your name: Ayesha Birth year: 2004 Hi Ayesha, you are about 22 years old.
cin >> stops reading at a space. To read a full line such as "Ayesha Khan", use getline(cin, name);.
Exercise
Exercise
Which type should you use to store the text "Karachi"?
